如何将类装饰器的方法添加到类中?我试过了
def add_decorator( cls ):
@dec
def update(self):
pass
cls.update = update
用法
add_decorator( MyClass )
MyClass.update()
但是MyClass.update没有装饰器
@dec不适用于更新
我正试图在sqlalchemy中使用orm.reconstructor.
解决方法:
如果你想在python> = 2.6中使用类装饰器,你可以这样做
def funkyDecorator(cls):
cls.funky = 1
@funkyDecorator
class MyClass(object):
pass
或者在python 2.5中
MyClass = funkyDecorator(MyClass)
但看起来你对方法装饰器感兴趣,你可以为此做到这一点
def logDecorator(func):
def wrapper(*args, **kwargs):
print "Before", func.__name__
ret = func(*args, **kwargs)
print "After", func.__name__
return ret
return wrapper
class MyClass(object):
@logDecorator
def mymethod(self):
print "xxx"
MyClass().mymethod()
输出:
Before mymethod
xxx
After mymethod
所以简而言之,你必须在方法定义之前放置@ orm.reconstructor
标签:python,decorator
来源: https://codeday.me/bug/20190518/1130291.html