In Python, why is list[] automatically global?

前端 未结 5 1388
你的背包
你的背包 2020-11-28 12:56

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 ,         


        
5条回答
  •  萌比男神i
    2020-11-28 13:29

    Here's an example that demonstrates that a non list/dict variable is available in a subroutine, and the problem is, as everyone says, the act of rebinding in your original code sample:

    x = 1
    def test():
        y = x + 1
        print y
    test()
    

    You'll see this prints out 2, despite x not being declared global.

提交回复
热议问题