In Python, why is list[] automatically global?

前端 未结 5 1389
你的背包
你的背包 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条回答
  •  隐瞒了意图╮
    2020-11-28 13:29

    If you had assigned a new value to rep_lst inside of test2 (not just to one of its elements, as you did) it would not work without the global flag. In Python, if you do not assign to a variable inside a function it will look for that variable in in more global scopes until it finds it.

    For example, in this code segment I define the list both globally and inside of example(). Since the variable in example() is closer in scope to example2() than the global one is, it is what will be used.

    x = ["out"]
    
    def example():
        x = ["in"]
        def example2():
            print x # will print ["in"]
    

    This has nothing to do with lists, but is the behaviour of any variable in Python.

提交回复
热议问题