装饰已用@classmethod装饰的Python方法,该方法调用另一个@classmethod

装饰已用@classmethod装饰的Python方法,该方法调用另一个@classmethod,python,oop,python-3.x,decorator,python-decorators,Python,Oop,Python 3.x,Decorator,Python Decorators,这是一个基本的Python问题。我正试图用我自己的装饰器,我的装饰器来装饰一个@classmethod。原来的@classmethod实际上在内部调用了另一个@classmethod。调用此内部方法时会出现问题,因为它依赖于cls参数。如果我的类始终是Foo,那么我可以用Foo.boo()替换任何调用,如cls.boo(),这将是很好的,但当我编写继承自Foo的子类时,这显然不是一个选择。下面是我想写的 def my_decorator(method): def redefined_me

这是一个基本的Python问题。我正试图用我自己的装饰器,我的装饰器来装饰一个
@classmethod
。原来的
@classmethod
实际上在内部调用了另一个
@classmethod
。调用此内部方法时会出现问题,因为它依赖于
cls
参数。如果我的类始终是
Foo
,那么我可以用
Foo.boo()
替换任何调用,如
cls.boo()
,这将是很好的,但当我编写继承自
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'

您忘记解包了
args

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

您忘记解包了
args

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

通常,您还将返回
method
返回的值。在这个版本中,不可能有返回值。@TomKarzes,哎呀,这是一个输入错误。很好的捕获。通常,您还将返回
method
返回的值。在这个版本中,不可能有返回值。@TomKarzes,哎呀,这是一个输入错误。接得好。