How do I add a method with a decorator to a class? I tried
def add_decorator( cls ):
@dec
def update(self):
pass
cls.update = update
usage
add_decorator( MyClass )
MyClass.update()
but MyClass.update does not have the decorator
@dec did not apply to update
I'm trying to use this with orm.reconstructor
in sqlalchemy.
If you want class decorator in python >= 2.6 you can do this
def funkyDecorator(cls):
cls.funky = 1
@funkyDecorator
class MyClass(object):
pass
or in python 2.5
MyClass = funkyDecorator(MyClass)
But looks like you are interested in method decorator, for which you can do this
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()
Output:
Before mymethod
xxx
After mymethod
So in short you have to just put @orm.reconstructor
before method definition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With