本文重点:解决了类里面定义的装饰器,在同一个类里面使用的问题,并实现了装饰器的类属性参数传递


目录:

一、基本装饰器

二、在类里定义装饰器,装饰本类内函数

三、类装饰器



正文:

一、基本装饰器

        装饰不带参数的函数

def clothes(func):
    def wear():
        print('Buy clothes!{}'.format(func.__name__))
        return func()
    return wear

@clothes
def body():
    print('The body feels could!')
    
#备注:@是语法糖
# 不用语法糖的情况下,使用下面语句也能实现装饰作用:把body再加工,再传给body
# body = clothes(body)

        装饰带一个参数的函数

def clothes(func):
    def wear(anything):            # 实际是定义一个anything参数,对应body函数参数
        print('Buy clothes!{}'.format(func.__name__))
        return func(anything)      # 执行func函数,并传入调用传入的anything参数
        # wear = func(anything)    # 在这一步,实际上可以看出来,为啥wear必须带参数,因为它就是func(anything)
    return wear
    # 所以clothes的结果是
    # clothes = wear = func(anything)
    # 不用语法糖的情况下就是
    # body = clothes(body)('hands')
    # 进一步证明:print(body.__name__)  显示的是wear函数
    
@clothes
def body(part):
    print('The body feels could!{}'.format(part))
    
body('hands'