python 类内部装饰器的实现

查看:157
本文介绍了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)

应该怎么实现呢?

解决方案

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

这篇关于python 类内部装饰器的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆