global在python_在Python中使用“global”关键字
在Python中使用“global”關鍵字
我從閱讀文檔中了解到,Python有一個單獨的函數命名空間,如果我想在該函數中使用全局變量,我需要使用global。
我正在使用Python 2.7,我嘗試了這個小測試
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
即使沒有global,似乎事情仍然正常。我能夠毫無問題地訪問全局變量。
我錯過了什么嗎? 另外,以下是來自Python文檔:
全局聲明中列出的名稱?? 不得被定義為正式的?? 參數或for循環控制?? 目標,類定義,功能?? 定義或導入語句。
雖然形式參數和類定義對我有意義,但我無法理解for循環控制目標和函數定義的限制。
10個解決方案
328 votes
關鍵字global僅對在本地上下文中更改或創建全局變量很有用,盡管創建全局變量很少被認為是一個很好的解決方案。
def bob():
me = "locally defined" # Defined only in local context
print me
bob()
print me # Asking for a global variable
以上將給你:
locally defined
Traceback (most recent call last):
File "file.py", line 9, in
print me
NameError: name 'me' is not defined
如果使用global語句,則變量將在函數范圍“可用”之外,有效地成為全局變量。
def bob():
global me
me = "locally defined" # Defined locally but declared as global
print me
bob()
print me # Asking for a global variable
所以上面的代碼會給你:
locally defined
locally defined
此外,由于python的性質,您還可以使用global在本地上下文中聲明函數,類或其他對象。 雖然我會反對它,因為如果出現問題或需要調試它會導致噩夢。
unode answered 2019-02-17T23:11:32Z
192 votes
雖然您可以在不使用sub關鍵字的情況下訪問全局變量,但如果要修改它們,則必須使用global關鍵字。 例如:
foo = 1
def test():
foo = 2 # new local foo
def blub():
global foo
foo = 3 # changes the value of the global foo
在您的情況下,您只需訪問列表sub。
Ivo Wetzel answered 2019-02-17T23:12:03Z
66 votes
這是訪問名稱和在范圍內綁定它之間的區別。
如果您只是查找變量來讀取其值,則可以訪問全局和本地范圍。
但是,如果您為名稱不在本地范圍內的變量分配,則將該名稱綁定到此范圍(如果該名稱也作為全局存在,則會隱藏該名稱)。
如果您希望能夠分配全局名稱,則需要告訴解析器使用全局名稱而不是綁定新的本地名稱 - 這就是'global'關鍵字的作用。
綁定塊中的任何位置都會導致該塊中的所有名稱都被綁定,這可能會導致一些相當奇怪的后果(例如,UnboundLocalError突然出現在以前工作的代碼中)。
>>> a = 1
>>> def p():
print(a) # accessing global scope, no binding going on
>>> def q():
a = 3 # binding a name in local scope - hiding global
print(a)
>>> def r():
print(a) # fail - a is bound to local scope, but not assigned yet
a = 4
>>> p()
1
>>> q()
3
>>> r()
Traceback (most recent call last):
File "", line 1, in
r()
File "", line 2, in r
print(a) # fail - a is bound to local scope, but not assigned yet
UnboundLocalError: local variable 'a' referenced before assignment
>>>
pycruft answered 2019-02-17T23:12:54Z
47 votes
其他答案回答了你的問題。 關于Python中名稱的另一個重要事項是,它們在每個范圍的基礎上是本地的或全局的。
考慮一下,例如:
value = 42
def doit():
print value
value = 0
doit()
print value
您可能猜測value語句將分配給局部變量,而不會影響在value函數外聲明的同一變量的值。 您可能會更驚訝地發現上面的代碼無法運行。 函數內部的語句print value生成UnboundLocalError.
原因是Python注意到,在函數的其他地方,您指定了名稱value,并且value也沒有聲明為global。這使它成為局部變量。 但是當您嘗試打印它時,尚未定義本地名稱。 在這種情況下,Python不會像其他語言那樣回歸到將名稱作為全局變量查找。 實際上,如果在函數中的任何位置定義了同名的局部變量,則無法訪問全局變量。
kindall answered 2019-02-17T23:13:40Z
12 votes
訪問名稱和分配名稱是不同的。 在您的情況下,您只是訪問一個名稱。
如果分配給函數中的變量,則假定該變量是本地變量,除非您將其聲明為全局變量。 如果沒有,則假定它是全球性的。
>>> x = 1 # global
>>> def foo():
print x # accessing it, it is global
>>> foo()
1
>>> def foo():
x = 2 # local x
print x
>>> x # global x
1
>>> foo() # prints local x
2
user225312 answered 2019-02-17T23:14:12Z
6 votes
您可以訪問不含關鍵字global的全局關鍵字
為了能夠修改它們,您需要明確聲明關鍵字是全局的。 否則,關鍵字將在本地范圍內聲明。
例:
words = [...]
def contains (word):
global words #
return (word in words)
def add (word):
global words # must specify that we're working with a global keyword
if word not in words:
words += [word]
martynas answered 2019-02-17T23:14:46Z
2 votes
在函數外部聲明的任何變量都假定為全局變量,只有在從函數內部(構造函數除外)聲明它們時才必須指定該變量是全局變量。
Jesus Ramos answered 2019-02-17T23:15:11Z
0 votes
這意味著您不應該執行以下操作:
x = 1
def myfunc():
global x
# formal parameter
def localfunction(x):
return x+1
# import statement
import os.path as x
# for loop control target
for x in range(10):
print x
# class definition
class x(object):
def __init__(self):
pass
#function definition
def x():
print "I'm bad"
ikostia answered 2019-02-17T23:15:37Z
0 votes
全球使變量“全球”
def out():
global x
x = 1
print(x)
return
out()
print (x)
這使得'x'就像函數外的正常變量一樣。 如果你取出全局,那么它會產生錯誤,因為它無法在函數內打印變量。
def out():
# Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
x = 1
print(x)
return
out()
print (x)
Michael answered 2019-02-17T23:16:09Z
0 votes
我會舉個簡單的例子:想想這段代碼:
myVar = 0
print (myVar ) # 01 line: returns 0
def func():
myVar = "def"
print (myVar )
func() # 02 line: returns def
print (myVar ) # 03 line: returns 0
正如你所看到的最后一行代碼將返回0,因為在函數內部myVar變量沒有被重新分配,它只是被修改了它只會在調用函數時改變而不影響主myVar變量,因為它在里面定義了 我們的函數(意思是它是局部變量),但是使用全局關鍵字:
myVar = 0
print (myVar ) # 01 Line : returns 0
def func():
global myVar
myVar = "def"
print (myVar )
func() # 02 Line : returns def
print (myVar ) # 03 Line : returns def
我們實際上命令python,def中的這個變量不是本地的,使用名為myVar的全局變量來改變它。
a_m_dev answered 2019-02-17T23:16:48Z
總結
以上是生活随笔為你收集整理的global在python_在Python中使用“global”关键字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AI 认定他在千里之外作了案,送进监狱关
- 下一篇: python输出矩阵的转置_Python