How do I add a method with a decorator to a class in python?
decorator, python
Solution
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
Problem
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.