# nested functions defouterFunction(text):
text = text
definnerFunction():print(text)
innerFunction()if __name__ =='__main__':
outerFunction('Hey !')# 只有当外层函数被调用时,内部函数才会被调用
关于在内部函数访问外部函数的变量时候,会发生什么?
defouterFunction():
s ='I love CJLU'definnerFunction():
s='I don\'t like CJLU'print(f'inner:{s}')
innerFunction()print(f'outter:{s}')if __name__ =='__main__':
outerFunction()
这时候上述函数的输出outter的s仍为I love CJLU,说明内嵌函数(inner function)使用的变量s是一个局部的变量,这一点和上一条函数直接修改和全局变量同名的函数时一样的
# defining a decoratordefhello_decorator(func):definner1():print("Hello, this is before function execution")# 第5步调用function_to_be_used
func()print("This is after function execution")# 第2步略过内嵌函数,直接返回inner1 return inner1
deffunction_to_be_used():# 第5步调用function_to_be_usedprint("This is inside the function !!")if __name__=='__main__':# 第1步调用hello_decorator# 第3步function_to_be_used=inner1
function_to_be_used = hello_decorator(function_to_be_used)# 第4步调用function_to_be_used--->调用inner1
function_to_be_used()# 第6步执行完function_to_be_used