2015-11-05 89 views
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 

但很明顯,我真正想要的是它來檢查數字的範圍。

我該如何做到這一點?

+0

'高清my_func,並將(X,數=數,N = N):' –

+0

但是你打電話每次都有3個硬編碼 - >'f(3)' – wim

+0

@wim他的問題在於'n'變量,他希望每個閉包都有所不同。 – Barmar

回答

2

解決方案(通常情況下)是不使用全局變量(或非本地變量)。你的函數的輸入應該來自參數,輸出應該是返回值。至於構建功能我會用某種廠..

在這種情況下,我會寫:

def comparison_factory(compare_to): 
    def compare_func(x): 
     res = x < compare_to 
     print("is {} less than {}? {}".format(x, compare_to, res)) 
     return res 
    return compare_func 

funcs = [ comparison_factory(n) for n in range(1,5) ] 

for f in funcs: 
    f(3)