- 分析:
- 在内层函数中,可以通过闭包的特性获取外层函数传递的参数。对于默认参数,无论外层函数如何调用,只要内层函数没有重新定义同名参数,就会使用外层函数定义时的默认值。对于可选参数,如果外层函数调用时传入了该可选参数的值,内层函数就能获取到传入的值;如果外层函数没有传入,就会使用外层函数定义时的默认值。
- 代码验证:
def outer_function(a, b=10, c=None):
def inner_function():
print(f"a: {a}, b: {b}, c: {c}")
return inner_function
# 场景一:不传入可选参数c
inner_func1 = outer_function(5)
inner_func1()
# 输出: a: 5, b: 10, c: None
# 场景二:传入可选参数c
inner_func2 = outer_function(5, c='test')
inner_func2()
# 输出: a: 5, b: 10, c: test
# 场景三:修改默认参数b的值
inner_func3 = outer_function(5, b = 20)
inner_func3()
# 输出: a: 5, b: 20, c: None