在 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 don't
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()
为什么list不需要声明global?它们是自动全局的吗?
Why list do not need to declare global? are they automatically global?
我觉得这真的很奇怪,我大部分时间都使用列表,我什至根本不使用 global 将它们作为全局...
I find it really weird, I use list most of the time and I don't even use global at all to us them as global...
推荐答案
它不是自动全局的.
然而,rep_i=1
和 rep_lst[0]=1
之间有区别——前者重新绑定了名称 rep_i
,所以 <需要 code>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屋!