我有兩個全局變量,一個int和另一個列表。 我可以修改其中一個函數定義中的列表,但不能修改int(不使用全局語句)。全局範圍因數據類型而異
i = 2000
lst = range(0,3)
def AddM():
i=i+1
lst.append(10)
這是什麼原因?
我有兩個全局變量,一個int和另一個列表。 我可以修改其中一個函數定義中的列表,但不能修改int(不使用全局語句)。全局範圍因數據類型而異
i = 2000
lst = range(0,3)
def AddM():
i=i+1
lst.append(10)
這是什麼原因?
答案比你想像的要簡單得多。
您需要了解如何在此處使用全局聲明。 請參閱相關文檔,並仔細閱讀:
全局()是一個包含所有的全局變量的字典: 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
玩得開心。
作爲蟒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
全局隻影響範圍和名稱解析。這裏列出你只是修改已經存在的列表並附加新元素,這就是爲什麼你不需要將其定義爲全局的原因。
[爲什麼當變量有值時會得到'UnboundLocalError]?](https://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror當這個變量有一個值) –
有關這方面的問題,請搜索StackOverflow。提示:'='與'append'不一樣。 – BrenBarn