global在python_在Python中使用“global”关键字
在Python中使用“global”關(guān)鍵字
我從閱讀文檔中了解到,Python有一個(gè)單獨(dú)的函數(shù)命名空間,如果我想在該函數(shù)中使用全局變量,我需要使用global。
我正在使用Python 2.7,我嘗試了這個(gè)小測(cè)試
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
即使沒(méi)有g(shù)lobal,似乎事情仍然正常。我能夠毫無(wú)問(wèn)題地訪問(wèn)全局變量。
我錯(cuò)過(guò)了什么嗎? 另外,以下是來(lái)自Python文檔:
全局聲明中列出的名稱?? 不得被定義為正式的?? 參數(shù)或for循環(huán)控制?? 目標(biāo),類(lèi)定義,功能?? 定義或?qū)胝Z(yǔ)句。
雖然形式參數(shù)和類(lèi)定義對(duì)我有意義,但我無(wú)法理解for循環(huán)控制目標(biāo)和函數(shù)定義的限制。
10個(gè)解決方案
328 votes
關(guān)鍵字global僅對(duì)在本地上下文中更改或創(chuàng)建全局變量很有用,盡管創(chuàng)建全局變量很少被認(rèn)為是一個(gè)很好的解決方案。
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語(yǔ)句,則變量將在函數(shù)范圍“可用”之外,有效地成為全局變量。
def bob():
global me
me = "locally defined" # Defined locally but declared as global
print me
bob()
print me # Asking for a global variable
所以上面的代碼會(huì)給你:
locally defined
locally defined
此外,由于python的性質(zhì),您還可以使用global在本地上下文中聲明函數(shù),類(lèi)或其他對(duì)象。 雖然我會(huì)反對(duì)它,因?yàn)槿绻霈F(xiàn)問(wèn)題或需要調(diào)試它會(huì)導(dǎo)致噩夢(mèng)。
unode answered 2019-02-17T23:11:32Z
192 votes
雖然您可以在不使用sub關(guān)鍵字的情況下訪問(wèn)全局變量,但如果要修改它們,則必須使用global關(guān)鍵字。 例如:
foo = 1
def test():
foo = 2 # new local foo
def blub():
global foo
foo = 3 # changes the value of the global foo
在您的情況下,您只需訪問(wèn)列表sub。
Ivo Wetzel answered 2019-02-17T23:12:03Z
66 votes
這是訪問(wèn)名稱和在范圍內(nèi)綁定它之間的區(qū)別。
如果您只是查找變量來(lái)讀取其值,則可以訪問(wèn)全局和本地范圍。
但是,如果您為名稱不在本地范圍內(nèi)的變量分配,則將該名稱綁定到此范圍(如果該名稱也作為全局存在,則會(huì)隱藏該名稱)。
如果您希望能夠分配全局名稱,則需要告訴解析器使用全局名稱而不是綁定新的本地名稱 - 這就是'global'關(guān)鍵字的作用。
綁定塊中的任何位置都會(huì)導(dǎo)致該塊中的所有名稱都被綁定,這可能會(huì)導(dǎo)致一些相當(dāng)奇怪的后果(例如,UnboundLocalError突然出現(xiàn)在以前工作的代碼中)。
>>> 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
其他答案回答了你的問(wèn)題。 關(guān)于Python中名稱的另一個(gè)重要事項(xiàng)是,它們?cè)诿總€(gè)范圍的基礎(chǔ)上是本地的或全局的。
考慮一下,例如:
value = 42
def doit():
print value
value = 0
doit()
print value
您可能猜測(cè)value語(yǔ)句將分配給局部變量,而不會(huì)影響在value函數(shù)外聲明的同一變量的值。 您可能會(huì)更驚訝地發(fā)現(xiàn)上面的代碼無(wú)法運(yùn)行。 函數(shù)內(nèi)部的語(yǔ)句print value生成UnboundLocalError.
原因是Python注意到,在函數(shù)的其他地方,您指定了名稱value,并且value也沒(méi)有聲明為global。這使它成為局部變量。 但是當(dāng)您嘗試打印它時(shí),尚未定義本地名稱。 在這種情況下,Python不會(huì)像其他語(yǔ)言那樣回歸到將名稱作為全局變量查找。 實(shí)際上,如果在函數(shù)中的任何位置定義了同名的局部變量,則無(wú)法訪問(wèn)全局變量。
kindall answered 2019-02-17T23:13:40Z
12 votes
訪問(wèn)名稱和分配名稱是不同的。 在您的情況下,您只是訪問(wèn)一個(gè)名稱。
如果分配給函數(shù)中的變量,則假定該變量是本地變量,除非您將其聲明為全局變量。 如果沒(méi)有,則假定它是全球性的。
>>> 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
您可以訪問(wèn)不含關(guān)鍵字global的全局關(guān)鍵字
為了能夠修改它們,您需要明確聲明關(guān)鍵字是全局的。 否則,關(guān)鍵字將在本地范圍內(nèi)聲明。
例:
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
在函數(shù)外部聲明的任何變量都假定為全局變量,只有在從函數(shù)內(nèi)部(構(gòu)造函數(shù)除外)聲明它們時(shí)才必須指定該變量是全局變量。
Jesus Ramos answered 2019-02-17T23:15:11Z
0 votes
這意味著您不應(yīng)該執(zhí)行以下操作:
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'就像函數(shù)外的正常變量一樣。 如果你取出全局,那么它會(huì)產(chǎn)生錯(cuò)誤,因?yàn)樗鼰o(wú)法在函數(shù)內(nèi)打印變量。
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
我會(huì)舉個(gè)簡(jiǎn)單的例子:想想這段代碼:
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,因?yàn)樵诤瘮?shù)內(nèi)部myVar變量沒(méi)有被重新分配,它只是被修改了它只會(huì)在調(diào)用函數(shù)時(shí)改變而不影響主myVar變量,因?yàn)樗诶锩娑x了 我們的函數(shù)(意思是它是局部變量),但是使用全局關(guān)鍵字:
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
我們實(shí)際上命令python,def中的這個(gè)變量不是本地的,使用名為myVar的全局變量來(lái)改變它。
a_m_dev answered 2019-02-17T23:16:48Z
總結(jié)
以上是生活随笔為你收集整理的global在python_在Python中使用“global”关键字的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: AI 认定他在千里之外作了案,送进监狱关
- 下一篇: python输出矩阵的转置_Python