【python 第五日】 函数闭包与装饰器

装饰器:本质就是函数,功能室为其他函数添加附加功能

原则:

1、不修改原函数的调用方式

2、不修改原函数的源代码

多重修饰器

def first(func):
    print('%s() was post to first()' % func.__name__)

    def _first(*args, **kw):
        print('Call the function %s() in _first().' % func.__name__)
        return func(*args, **kw)

    return _first


def second(func):
    print('%s() was post to second()' % func.__name__)

    def _second(*args, **kw):
        print('Call the function %s() in _second().' % func.__name__)
        return func(*args, **kw)

    return _second


@first
@second
def test():
    return 'hello world'

test()


#输出如下
test() was post to second()
_second() was post to first()
Call the function _second() in _first().
Call the function test() in _second().

猜你喜欢

转载自www.cnblogs.com/zhouguanglu/p/10178438.html