在Python中,为什么list []是自动全局的? [英] In Python, why is list[] automatically global?
问题描述
这是一个奇怪的行为.
尝试一下:
rep_i=0
print "rep_i is" , rep_i
def test():
global rep_i #without Global this gives error but list , dict , and others dont
if rep_i==0:
print "Testing Integer %s" % rep_i
rep_i=1
return "Done"
rep_lst=[1,2,3]
def test2():
if rep_lst[0]==1:
print "Testing List %s" % rep_lst
return "Done"
if __name__=="__main__":
test()
test2()
为什么列表不需要全局声明?它们是自动全局的吗?
Why list do not need to declare global? are they automatically global?
我发现它真的很奇怪,我大部分时间都使用列表,甚至根本不使用global作为全局.....
I find it really wierd , i use list most of the time and i dont even use global at all to us them as global .....
推荐答案
它不是自动全局的.
但是,rep_i=1
和rep_lst[0]=1
之间有区别-前者重新绑定了名称rep_i
,因此需要global
来防止创建相同名称的本地插槽.在后一种情况下,您只是在修改现有的全局对象,该对象可以通过常规名称查找找到(更改列表条目就像在列表上调用成员函数一样,而不是重新绑定名称).
However, there's a difference between rep_i=1
and rep_lst[0]=1
- the former rebinds the name rep_i
, so global
is needed to prevent creation of a local slot of the same name. In the latter case, you're just modifying an existing, global object, which is found by regular name lookup (changing a list entry is like calling a member function on the list, it's not a name rebinding).
要对其进行测试,请尝试在test2
中分配rep_lst=[]
(即,将其设置为新列表).除非您声明rep_lst
global
,否则在test2
外部将看不到效果,因为会创建相同名称的本地插槽并遮盖全局插槽.
To test it out, try assigning rep_lst=[]
in test2
(i.e. set it to a fresh list). Unless you declare rep_lst
global
, the effects won't be visible outside test2
because a local slot of the same name is created and shadows the global slot.
这篇关于在Python中,为什么list []是自动全局的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!