defhi(name="yasoob"): defgreet(): return"now you are in the greet() function" defwelcome(): return"now you are in the welcome() function" if name == "yasoob": return greet else: return welcome a = hi() print(a) #outputs: <function greet at 0x7f2143c01500> #上面清晰地展示了`a`现在指向到hi()函数中的greet()函数 #现在试试这个 print(a()) #outputs: now you are in the greet() function
函数的参数可以是函数对象
1 2 3 4 5 6 7 8 9 10
defhi(): return"hi yasoob!" defdoSomethingBeforeHi(func): print("I am doing some boring work before executing hi()") print(func())
doSomethingBeforeHi(hi) #outputs:I am doing some boring work before executing hi() # hi yasoob!
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 defa_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()
这段代码等价于…
1 2 3 4 5 6 7 8 9 10 11 12 13
@a_new_decorator defa_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)
但是,这样的代码存在的问题有,比如,__name__获取不到正确的函数名。
于是稍加修改,我们有了以下解释器函数的编写模板:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
from functools import wraps defa_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_decorator defa_function_requiring_decoration(): """Hey yo! Decorate me!""" print("I am the function which needs some decoration to " "remove my foul smell")