python 类内部装饰器的实现

学习装饰器的知识,想在类内部,实现一个装饰器

from functools import wraps
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('{} created!'.format(self.name))


    def freestyle(self, func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print('Yo Yo, this is my freestyle!')
            func(*args, **kwargs)
            print('Yo Yo end of my freestyle!')
        return wrapper


    @freestyle
    def self_introduce(self, style):
        print('my name is: {}'.format(self.name))
        print('I am {} years old'.format(self.age))
        print('My style: {}'.format(style))




def main():
    p1 = Person('Jack', 10)
    p1.self_introduce('jazz')


if __name__ == '__main__':
    main()

报错:

Traceback (most recent call last):
  File "learn_decorator.py", line 2, in <module>
    class Person:
  File "learn_decorator.py", line 18, in Person
    @freestyle
TypeError: freestyle() takes exactly 2 arguments (1 given)

应该怎么实现呢?

阅读 6.1k
2 个回答

哈哈,看到你这么幽默我都想笑。
def freestyle(func):
试试

新手上路,请多包涵

@freestyle(self=1)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题