print(my_sum(1, 'Hello')) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python 支持函数嵌套
1 2 3 4 5 6 7 8 9 10 11
deff1(): print('hello')
deff2(): # f2 is local to f1 print('world')
f2()
f1() f2() # NameError: name 'f2' is not defined
函数嵌套可以保证内部函数的隐私
内部函数只能被外部函数所调用和访问,不会暴露在全局作用域
合理地使用函数嵌套,可以提高程序的运行效率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
deffactorial(input): # validation check only once ifnotisinstance(input, int): raise Exception('input must be an integer.') ifinput < 0: raise Exception('input must be greater or equal to 0')
defvalidation_check(value): MIN_VALUE = 101# This is a local variable, shadowing the global variable print(MIN_VALUE) # 101 MIN_VALUE += 1 print(MIN_VALUE) # 102
definner(): nonlocal x # nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. x = 'nonlocal' print("inner:", x) # inner: nonlocal
inner() print("outer:", x) # outer: nonlocal
outer()
如果没有 nonlocal 关键字,并且内部函数的变量与外部函数的变量同名,则会覆盖
1 2 3 4 5 6 7 8 9 10 11 12
defouter(): x = "local"
definner(): x = 'nonlocal'# x is a local variable of inner function, shadowing the outer x print("inner:", x) # inner: nonlocal
inner() print("outer:", x) # outer: local
outer()
闭包
Closure - 常与 Decorator 一起使用
与嵌套函数类似,但外部函数返回的是一个函数,而不是一个具体的值
返回的函数,可以被赋予一个变量,便于后续的执行调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defnth_power(exponent): defexponent_of(base): return base ** exponent