# 嵌套函数和变量作用域

## 嵌套函数

def TestFunc(val1):
val = val1

def innerFunc():
print(val)

innerFunc()

if __name__ == '__main__':
TestFunc('Hello world')


1. 函数的嵌套能够保证内部函数的隐私，内部函数只能在外部函数作用域内访问。
2. 合理的使用函数嵌套，能够提高程序的运行效率。

## 局部变量和全局变量

VALUE1 = 666

def TestFunc2():
global VALUE1
VALUE1 = VALUE1 + 1
print(VALUE1)

TestFunc2()
print(VALUE1)


667
667


VALUE1 = 666

def TestFunc3():
VALUE1 = 2
print(VALUE1)

TestFunc3()
print(VALUE1)


2
666


## 嵌套函数的变量作用域

def TestFunc():
val = 1
def innerFunc():
nonlocal val
val = 2
print("inner:",val)
innerFunc()
print("outer:", val)

TestFunc()


inner: 2
outer: 2


# 闭包

def nth_power(exponent):
def exponent_of(base):
return base ** exponent
return exponent_of

square = nth_power(2) # 平方
cube = nth_power(3) # 立方
print(square)
print(cube)

print(square(2))  # 2的平方
print(cube(2)) # 2的立方


<function nth_power.<locals>.exponent_of at 0x000001E9629C04C8>
<function nth_power.<locals>.exponent_of at 0x000001E9629C0708>
4
8


def nth_power(exponent):
def exponent_of(base):
return base ** exponent
return exponent_of

square = nth_power(2) # 平方
print(square(2)) # 2的平方

del nth_power
print(square(3)) # 3的平方


4
9



print(square)
print(cube)
print(square.__closure__)
print(square.__closure__[0].cell_contents)
print(cube.__closure__[0].cell_contents)


<function nth_power.<locals>.exponent_of at 0x000001DC127D04C8>
<function nth_power.<locals>.exponent_of at 0x000001DC127D0708>
(<cell at 0x000001DC124401F8: int object at 0x00007FFFA7FAA1B0>,)
2
3


# 总结

--THE END--

posted @ 2021-06-11 20:39  测试开发小记  阅读(145)  评论(0编辑  收藏  举报