defa_new_decorator(a_func):defwrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")return wrapTheFunctiondefa_function_requiring_decoration():print("I am the function which needs some decoration to remove my foul smell")a_function_requiring_decoration()#outputs: "I am the function which needs some decoration to remove my foul smell"a_function_requiring_decoration =a_new_decorator(a_function_requiring_decoration)#now a_function_requiring_decoration is wrapped by wrapTheFunction()a_function_requiring_decoration()#outputs:I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()
@a_new_decoratordefa_function_requiring_decoration():"""Hey you! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function_requiring_decoration()#outputs: I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()#the @a_new_decorator is just a short way of saying:a_function_requiring_decoration =a_new_decorator(a_function_requiring_decoration)
from functools import wrapsdefa_new_decorator(a_func):@wraps(a_func)defwrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")return wrapTheFunction@a_new_decoratordefa_function_requiring_decoration():"""Hey yo! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")print(a_function_requiring_decoration.__name__)# Output: a_function_requiring_decoration
现在好多了。我们接下来学习装饰器的一些常用场景。
蓝本规范:
from functools import wrapsdefdecorator_name(f):@wraps(f)defdecorated(*args,**kwargs):ifnot can_run:return"Function will not run"returnf(*args, **kwargs)return decorated@decorator_namedeffunc():return("Function is running")can_run =Trueprint(func())# Output: Function is runningcan_run =Falseprint(func())# Output: Function will not run