菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
268
0

Python 装饰器备忘

原创
05/13 14:22
阅读数 28689
def deco(attr):
    ''' 装饰器,共包含三层返回结构 \n
        第一层:用于接收 @deco 的参数,此处的代码只在初始化装饰器时执行一次 \n
        第二层:用于接收 function,此处的代码只在初始化装饰器时执行一次 \n
        第三层:用于接收 function 的参数,并将作为最终被执行与返回的装饰结果 \n
    '''
    def _deco(f):
        '''第二层:用于接收 function,此处的代码只在初始化装饰器时执行一次
        '''
        print('只在装饰函数时,执行一次,此时装饰函数', f.__name__)

        def __deco(a, b):
            '''第三层:用于接收 function 的参数,并将作为最终被执行与返回的装饰结果
            '''
            print('before run attr: ' + attr + '; a: ' + a + '; b: ' + b)
            # 此处必须调用 function,不然装饰器执行过后,就不会再执行 function 的函数体
            f(a, b)
            print('after  run attr: ' + attr + '; a: ' + a + '; b: ' + b)

        return __deco
    return _deco


@deco('hello')
def hello(a, b):
    print('hello, ' + a + b)


@deco('world')
def world(a, b):
    print('world, ' + a + b)


hello('a', 'b')
world('A', 'B')


# 执行结果:
# 
# 只在装饰函数时,执行一次,此时装饰函数 hello
# 只在装饰函数时,执行一次,此时装饰函数 world
# before run attr: hello; a: a; b: b
# hello, ab
# after  run attr: hello; a: a; b: b
# before run attr: world; a: A; b: B
# world, AB
# after  run attr: world; a: A; b: B

发表评论

0/200
268 点赞
0 评论
收藏