0
我的代碼是這樣的:解決方法覆蓋for循環中的局部變量?
funcs = []
class NumberContainer():
def __init__(self, num):
self.number = num
items = []
for i in range(5):
items.append(NumberContainer(i+1))
for item in items:
number = item.number
n = number
def my_func(x):
res = x < n
print("is {} less than {}? {}".format(x, number, res))
return res
funcs.append(my_func)
for f in funcs:
f(3)
此輸出:
is 3 less than 5? True
is 3 less than 5? True
is 3 less than 5? True
is 3 less than 5? True
is 3 less than 5? True
但很明顯,我真正想要的是它來檢查數字的範圍。
我該如何做到這一點?
'高清my_func,並將(X,數=數,N = N):' –
但是你打電話每次都有3個硬編碼 - >'f(3)' – wim
@wim他的問題在於'n'變量,他希望每個閉包都有所不同。 – Barmar