python 全局列表,在Python中,为什么list []是自动全局的?

This is a weird behavior.

Try this :

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?

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 .....

解决方案

It isn't automatically 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).

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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值