例如:
def aaa():
a=False
print id(a)
def waiting():
global a
a=True
print id(a)
waiting()
print id(a)
return a
if __name__ == "__main__":
print aaa()
结果为False
看似waiting()中global a能调用aaa()中的a, 实则不然, 看似global到外面一层, 实则global只作用于最外层的全局变量, 所以waiting()中的global a指的是aaa()函数外的变量a, 与aaa()中的无关.
实现方法:
def aaa():
global a
a=False
print id(a)
def waiting():
global a
a=True
print id(a)
waiting()
print id(a)
return a
if __name__ == "__main__":
print aaa()
而真正的函数嵌套是这样子的
def multiplier(factor):
def multiplyByFactor(number):
return number*factor
return multiplyByFactor
>>>double = multiplier(2)
>>>double(5)
10
>>>triple=multiplier(3)
>>>triple(3)
9
>>>multiplier(5)(4)
>>>20