In Python, why is list[] automatically global?

前端 未结 5 1385
你的背包
你的背包 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:44

    There is an error in python called UnboundLocalError which often confuses newcomers. The confusing thing is: future assignment does change the way a variable is looked up.

    When the interpreter sees a variable name for the first time, it looks ahead to the end of current code block, and if you don't have an assignment to it anywhere within the same block of code, the interpreter considers it global. If you do, however, then it is considered local, and any reference to it before assignment generates an UnboundLocalError. That's the error you got. That's why you need to declare global rep_i. If you did not assign rep_i, you wouldn't need this line.

    Also, this has nothing to do with variable type. Also, assigning or appending an item to the list (which you probably meant to do, but did not) is not assignment of the list itself, it is essentially calling a method on a list object, which is different from assignment: assignment creates a new object (possibly under a name that already exists), while manipulating a list just changes an existing list. You can try:

    In [1]: # It won't work with small integers, as they are cached singletons in CPython
    
    In [2]: a = 123123
    
    In [3]: id (a)
    Out[3]: 9116848
    
    In [4]: a = 123123
    
    In [5]: id(a)
    Out[5]: 9116740
    
    In [6]: # See, it changed
    
    In [7]: # Now with lists
    
    In [8]: l = [1,2,3]
    
    In [9]: id(l)
    Out[9]: 19885792
    
    In [10]: l[1] = 2
    
    In [11]: id(l)
    Out[11]: 19885792
    
    In [12]: # See, it is the same
    
    In [13]: # But if i reassign the list, even to the same value
    
    In [14]: l = [2,2,3]
    
    In [15]: id(l)
    Out[15]: 19884272
    

提交回复
热议问题