Python类成员的装饰器在装饰器机制是一个类时会失败

7
当我在为类方法创建装饰器时,如果装饰器机制是一个类而不是函数/闭包,我会遇到问题。当使用类形式时,我的装饰器不会被视为绑定方法。
通常我喜欢使用函数形式的装饰器,但在这种情况下,我必须使用现有的类来实现我需要的功能。
这似乎与python-decorator-makes-function-forget-that-it-belongs-to-a-class有关,但为什么函数形式可以正常工作呢?
以下是我能够展示所有过程的最简单的示例代码。对于代码量的问题我很抱歉:
def decorator1(dec_param):
    def decorator(function):
        print 'decorator1 decoratoring:', function
        def wrapper(*args):
            print 'wrapper(%s) dec_param=%s' % (args, dec_param)
            function(*args)
        return wrapper
    return decorator

class WrapperClass(object):
    def __init__(self, function, dec_param):
        print 'WrapperClass.__init__ function=%s dec_param=%s' % (function, dec_param)
        self.function = function
        self.dec_param = dec_param

    def __call__(self, *args):
        print 'WrapperClass.__call__(%s, %s) dec_param=%s' % (self, args, self.dec_param)
        self.function(*args)

def decorator2(dec_param):
    def decorator(function):
        print 'decorator2 decoratoring:', function
        return WrapperClass(function, dec_param)
    return decorator

class Test(object):
    @decorator1(dec_param=123)
    def member1(self, value=1):
        print 'Test.member1(%s, %s)' % (self, value)

    @decorator2(dec_param=456)
    def member2(self, value=2):
        print 'Test.member2(%s, %s)' % (self, value)

@decorator1(dec_param=123)
def free1(value=1):
    print 'free1(%s)' % (value)

@decorator2(dec_param=456)
def free2(value=2):
    print 'free2(%s)' % (value)

test = Test()
print '\n====member1===='
test.member1(11)

print '\n====member2===='
test.member2(22)

print '\n====free1===='
free1(11)

print '\n====free2===='
free2(22)

输出:

decorator1 decoratoring: <function member1 at 0x3aba30>
decorator2 decoratoring: <function member2 at 0x3ab8b0>
WrapperClass.__init__ function=<function member2 at 0x3ab8b0> dec_param=456
decorator1 decoratoring: <function free1 at 0x3ab9f0>
decorator2 decoratoring: <function free2 at 0x3ab970>
WrapperClass.__init__ function=<function free2 at 0x3ab970> dec_param=456

====member1====
wrapper((<__main__.Test object at 0x3af5f0>, 11)) dec_param=123
Test.member1(<__main__.Test object at 0x3af5f0>, 11)

====member2====
WrapperClass.__call__(<__main__.WrapperClass object at 0x3af590>, (22,)) dec_param=456
Test.member2(22, 2)        <<<- Badness HERE!

====free1====
wrapper((11,)) dec_param=123
free1(11)

====free2====
WrapperClass.__call__(<__main__.WrapperClass object at 0x3af630>, (22,)) dec_param=456
free2(22)

1
我建议重新命名这个问题。实际上这与装饰器没有太大关系,而是关于将一个函数对象添加为类方法的问题。 - Casebash
通常(尽管不总是如此),当一个问题很长时,通过隔离问题可以简化它。例如,如果您尝试手动注释类,就会意识到它与装饰器无关,而且这样做可能比输入所有代码更快。 - Casebash
1个回答

10

你的WrapperClass需要是一个描述符(就像函数一样!),也就是说,提供适当的特殊方法__get____set__这份指南将教你一切需要了解的内容!-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接