2010-04-24 69 views
5

如何添加装饰器的方法到类中?我试图如何添加一个装饰器的方法到Python中的类?

def add_decorator(cls): 
    @dec 
    def update(self): 
     pass 

    cls.update = update 

使用

add_decorator(MyClass) 

MyClass.update() 

但MyClass.update不具有装饰

@dec并不适用于更新

我试图用orm.reconstructor使用在sqlalchemy。

+0

我搞掂你的问题,以反映它好像你问之前 - 但如果我完全误解了你的意图,随时回滚编辑并自己澄清。 – 2010-04-24 04:17:43

回答

6

如果你想在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方法定义

0

在代表你的SQL记录类,

from sqlalchemy.orm import reconstructor 

class Thing(object): 
    @reconstructor 
    def reconstruct(self): 
     pass 
相关问题