2014-04-01 18 views
0

我有兩個全局變量,一個int和另一個列表。 我可以修改其中一個函數定義中的列表,但不能修改int(不使用全局語句)。全局範圍因數據類型而異

i = 2000 
lst = range(0,3) 

def AddM(): 
    i=i+1 
    lst.append(10) 

這是什麼原因?

+0

[爲什麼當變量有值時會得到'UnboundLocalError]?](https://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror當這個變量有一個值) –

+0

有關這方面的問題,請搜索StackOverflow。提示:'='與'append'不一樣。 – BrenBarn

回答

0

答案比你想像的要簡單得多。

  1. 在你ADDM()函數,你實際上創建了一個名爲「新的」變量「i」的功能,這是一個函數中所做的任何新asignments默認命名空間的本地命名空間內。
  2. 已將本地「i」分配給「全局」i(您之前在全局命名空間中的函數之外定義的)的值,加上1。
  3. 然後你退出了你的功能,並且「沒有任何事情發生」給全球的「我」。 我會假設你這是你在這裏想知道的。

您需要了解如何在此處使用全局聲明。 請參閱相關文檔,並仔細閱讀:

全局()是一個包含所有的全局變量的字典: https://docs.python.org/2/library/functions.html#globals

Python中的「全局」關鍵字的用法: https://docs.python.org/2/reference/simple_stmts.html#the-global-statement

隨機例子我通過google找到了如何修復你的程序: stereochro.me/ideas/global-in-python

玩得開心。

0

作爲蟒DOC明確提到

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. 

定義該變量作爲全局的範圍。

>>> i = 2000 
>>> def AddM(): 
...  global i 
...  x += 1 
>>> p = AddM() 
>>>print p 
2001 

全局隻影響範圍和名稱解析。這裏列出你只是修改已經存在的列表並附加新元素,這就是爲什麼你不需要將其定義爲全局的原因。