2012-12-24 158 views

回答

9

您可以在Python 3使用nonlocal statement

>>> def f(): 
...  x = 2 
...  def y(): 
...   nonlocal x 
...   x += 3 
...   print(x) 
...  y() 
...  print(x) 
... 

>>> f() 
5 
5 

在Python 2,你需要聲明變量作爲外部函數的屬性來實現相同的。

>>> def f(): 
...  f.x = 2 
...  def y(): 
...   f.x += 3 
...   print(f.x) 
...  y() 
...  print(f.x) 
... 

>>> f() 
5 
5 

,或者使用我們還可以使用一個dictionarylist

>>> def f(): 
...  dct = {'x': 2} 
...  def y(): 
...   dct['x'] += 3 
...   print(dct['x']) 
...  y() 
...  print(dct['x']) 
... 

>>> f() 
5 
5 
+0

+1,但請注意,這僅適用於設置值,因此,如果你有外一個可變值範圍,可以從內部範圍對它進行變異。 –

+0

@Lattyware這就是我們爲什麼可以使用'dict'或'list'的原因,但是這看起來不錯。 –

+0

@AshwiniChaudhary事實上,除非數據結構是需要的,否則其他選項會更好。 –

相關問題