python - 带有类方法的类装饰器

标签 python decorator

我编写了一个类装饰器,它对一个类进行猴子修补,覆盖 init 并添加一个持久化方法 ()。到目前为止一切正常。

现在我需要向装饰类添加一个类方法(静态方法)。我必须在代码中更改哪些内容才能使 staticMethod() 成为装饰类的静态方法?

这是我的代码:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

class Persistent (object):
    def __init__ (self, table = None, rmap = None):
        self.table = table
        self.rmap = rmap

    def __call__ (self, cls):
        cls.table = self.table
        cls.rmap = self.rmap
        oinit = cls.__init__
        def finit (self, *args, **kwargs):
            print "wrapped ctor"
            oinit (self, *args, **kwargs)
        def persist (self):
            print "insert into %s" % self.table
            pairs = []
            for k, v in self.rmap.items (): pairs.append ( (v, getattr (self, k) ) )
            print "(%s)" % ", ".join (zip (*pairs) [0] )
            print "values (%s)" % ", ".join (zip (*pairs) [1] )
        def staticMethod (): print "I am static"
        cls.staticMethod = staticMethod
        cls.__init__ = finit
        cls.persist = persist
        return cls

@Persistent (table = "tblPerson", rmap = {"name": "colname", "age": "colage"} )
class Test (object):
    def __init__ (self, name, age):
        self.name = name
        self.age = age

a = Test ('John Doe', '23')
a.persist ()
Test.staticMethod ()

输出是:

wrapped ctor
insert into tblPerson
(colage, colname)
values (23, John Doe)
Traceback (most recent call last):
  File "./w2.py", line 39, in <module>
    Test.staticMethod ()
TypeError: unbound method staticMethod() must be called with Test instance as first argument (got nothing instead)

最佳答案

    @staticmethod
    def staticMethod (): print "I am static"

    def staticMethod (): print "I am static"
    cls.staticMethod = staticmethod(staticMethod)

关于python - 带有类方法的类装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6195698/

相关文章:

c# - 在 C# 中实现代理或装饰器类的最短方法是什么?

python - 在Maya中,有没有办法在翻滚过程中获取位置相机属性(旋转,平移)?

oop - 装饰器模式的正确使用

python - VS Code 找不到激活的 virtualenv

python - 中文字符在lua loadstring中吃掉其他字符

python - 在对象实例上使用装饰器(或其他一些模式)来生成类

python - 缓存装饰器 Python

Python设计问题(在这种情况下可以/应该使用装饰器吗?)

python - 如何在VCP模式下使用FDTI芯片?

python - Spark : IllegalArgumentException: 'Unsupported class file major version 55'