老男孩python学习自修第十七天【装饰器】

装饰器:在某个方法执行前后去执行其他新定义的行为

例如:

#!/usr/bin/env python
# _*_ coding:UTF-8 _*_

def before_say_hello():
    print "before hello"

def after_say_hello():
    print "after hello"

def say_hello_wrapper(func):
    def wrapper():
        print "Before"
        before_say_hello()
        func()
        print "After"
        after_say_hello()
    return wrapper

@say_hello_wrapper
def say_hello():
    print "Hello!"


if __name__ == "__main__":
    say_hello()

执行结果:

/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day14/decorator_test.py
Before
before hello
Hello!
After
after hello

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/liuzhiqaingxyz/p/9368836.html