装饰已经用@classmethod修饰的Python方法调用另一个@classmethod

时间:2015-12-11 19:21:41

标签: python oop python-3.x decorator python-decorators

这是一个基本的Python问题。我正在尝试使用自己的装饰器@classmethod来装饰my_decorator。原@classmethod实际上调用了另一个@classmethod。调用此内部方法时会出现问题,因为它取决于cls参数。如果我的cls.boo()调用Foo.boo(),如果我的类总是Foo,那么这样就可以了,但是当我编写继承自{的子类时,这显然不是一个选择。 {1}}。以下是我想写的内容。

Foo

我期待以下输出。

def my_decorator(method):
    def redefined_method(*args, **kwargs):
        print('Starting decorator')
        result = method(args, **kwargs)
        return result
    return redefined_method

class Foo(object):        
    @classmethod
    def boo(cls):
        print('Running from Foo\'s boo')

    @classmethod
    @my_decorator
    def bar(cls):
        print('Running from Foo\'s bar')
        '''
        Replacing the following line with 'Foo.boo()'
        produces no errors when calling `Foo.bar()`, 
        but then we can't run Child's version of the boo method.
        ''' 
        cls.boo()

class Child(Foo):
    @classmethod
    def boo(cls):
        print('Running from Child\'s version of boo')

if __name__ == '__main__':
    Foo.bar()    
    Child.bar()

当前输出。

Starting decorator
Running from Foo's bar
Running from Foo\'s boo
Starting decorator
Running from Foo's bar
Running from Child\'s version of boo

我尝试切换Starting decorator Running from Foo's bar Traceback (most recent call last): File "C:\....\dec_example.py", line 29, in <module> Foo.bar() File "C:\....\dec_example.py", line 4, in redefined_method method(args, **kwargs) File "C:\....\dec_example.py", line 21, in bar cls.boo() AttributeError: 'tuple' object has no attribute 'boo' @classmethod的顺序,但它仍然无效并产生以下堆栈跟踪。

@my_decorator

1 个答案:

答案 0 :(得分:3)

您忘了解包args

def my_decorator(method):
    def redefined_method(*args, **kwargs):
        print('Starting decorator')
        method(args, **kwargs)
        # here ^, no star!
    return redefined_method