如何在python中向类中添加带装饰器的方法?

Tim*_*mmy 5 python decorator

如何将类装饰器的方法添加到类中?我试过了

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

    cls.update = update
Run Code Online (Sandbox Code Playgroud)

用法

 add_decorator( MyClass )

 MyClass.update()
Run Code Online (Sandbox Code Playgroud)

但是MyClass.update没有装饰器

@dec不适用于更新

我想orm.reconstructor在sqlalchemy中使用它.

Anu*_*yal 6

如果你想在python> = 2.6中使用类装饰器,你可以这样做

def funkyDecorator(cls):
    cls.funky = 1

@funkyDecorator
class MyClass(object):
    pass
Run Code Online (Sandbox Code Playgroud)

或者在python 2.5中

MyClass = funkyDecorator(MyClass)
Run Code Online (Sandbox Code Playgroud)

但看起来你对方法装饰器感兴趣,你可以为此做到这一点

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()
Run Code Online (Sandbox Code Playgroud)

输出:

Before mymethod
xxx
After mymethod
Run Code Online (Sandbox Code Playgroud)

所以简而言之,你必须@orm.reconstructor在方法定义之前