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 hi.<locals>.greet at 0x000000B36FE96488>
#上面清晰地展示了`a`现在指向到hi()函数中的greet()函数 #现在试试这个 #outputs: now you are in the greet() function
再次看看这个代码。在 if/else 语句中我们返回 greet 和 welcome,而不是 greet() 和 welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行; 然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。 当我们写下 a = hi(),hi() 会被执行,而由于 name 参数默认是 yasoob,所以函数 greet 被返回了。如果我们把语句改为 a = hi(name = “ali”),那么 welcome 函数将被返回。我们还可以打印出 hi()(),这会输出 now you are in the greet() function。
2.将函数作为参数传给另一个函数
1 2 3 4 5 6 7 8
defhi(): print('Hello Big data industry!!!!!')
defdosomethingBeforehi(func): print("I am echo!!!!!!") 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
defa_function_requiring_decoration(): print("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()
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 wrapTheFunction @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()