我正在尝试编写一些代码,定义外部函数包括内部函数。
def outer():
t = 1
for i in range(3):
print(f'## {i}th loop##')
t = inner(t)
return t
def inner(t):
print(f't value is now {t}')
t += 1
if (t % 10) != 0: # imaginary if-condition to reproduce my original codes
inner(t)
return t
outer()
在这样做的过程中,我遇到了一个问题,即多次实现内部函数不会同时改变与外部函数定义定义的变量值。
以上代码的结果为: 结果
第一iter t: 1, 2, 3, 4, 5, 6, 7, 8, 9
第二iter t: 2, 3, 4, 5, 6, 7, 8, 9 . .
我期望第二次迭代中的t值将从值10开始。你能告诉我是什么问题吗?
问题是如何调用:
外>→内的→内的→最后内心等。导致最后一次内部调用的t += 1。
如果你想让它正常工作,并且仍然使用内部和外部,你可以这样做:
def outer():
t = 0
for i in range(3):
print(f'## {i}th loop##')
t = inner(t)
def inner(num):
for j in range(num, num + 10):
print(f't value is now {j}')
num += 1
return num
outer()
本刊:
inner(t)
递归调用中的更改对父变量没有影响——参见如何通过引用传递变量?
可以修改为:
t = inner(t)
代码就变成:
def outer():
t = 1
for i in range(3):
print(f'## {i}th loop##')
t = inner(t)
return t
def inner(t):
print(f't value is now {t}')
t += 1 # equivalent to t = t + 1
# which creates a new local value of t and assigns it to passed in argument t + 1
if (t % 10) != 0: # imaginary if-condition to reproduce my original codes
t = inner(t)
return t
outer()
## 0th loop##
t value is now 1
t value is now 2
t value is now 3
t value is now 4
t value is now 5
t value is now 6
t value is now 7
t value is now 8
t value is now 9
## 1th loop##
t value is now 10
t value is now 11
t value is now 12
t value is now 13
t value is now 14
t value is now 15
t value is now 16
t value is now 17
t value is now 18
t value is now 19
## 2th loop##
t value is now 20
t value is now 21
t value is now 22
t value is now 23
t value is now 24
t value is now 25
t value is now 26
t value is now 27
t value is now 28
t value is now 29