所谓的装饰器,其实就是通过装饰器函数,来修改原函数的一些功能,使得原函数不需要修改。
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper def say_whee(): print("Whee!") say_whee = my_decorator(say_whee) >>> say_whee() Something is happening before the function is called. Whee! Something is happening after the function is called.
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_whee(): print("Whee!")
def my_decorator(func): def wrapper(people_name): print("这是装饰后具有的新输出") func(people_name) return wrapper @my_decorator def hello(people_name): print("你好,{}".format(people_name)) hello("张三") #输出: #这是装饰后具有的新输出 #你好,张三
def my_decorator(func): def wrapper(*args, **kwargs): print("这是装饰后具有的新输出") func(*args, **kwargs) return wrapper
def Interrupt_exception(func): def wrapper(*args, **kwargs): try: result = func(*args, **kwargs) return result except KeyboardInterrupt: print("手动停止") os._exit(0) return wrapper
其他更多,详见:把苹果咬哭的测试笔记专栏