defhi(name="yasoob"): print("now you are inside the hi() function")
defgreet(): return"now you are in the greet() function"
defwelcome(): return"now you are in the welcome() function"
print(greet()) print(welcome()) print("now you are back in the hi() function")
hi() #output:now you are inside the hi() function # now you are in the greet() function # now you are in the welcome() function # now you are back in the hi() function
当我们写下 **a = hi()**,hi() 会被执行,而由于 name 参数默认是 yasoob,所以函数 greet 被返回了。如果我们把语句改为 **a = hi(name = “ali”)**,那么 welcome 函数将被返回。我们还可以打印出 **hi()()**,这会输出 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()
@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)
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")