可变与不变的全局

时间:2019-10-20 01:00:42

标签: python global

以下是对可变对象和不可变对象上的global的正确理解吗?

immutable1 = 'abc'
immutable2 = '123'
mutable = {}

def change():    
    mutable['CHANGED'] = 'CHANGED' # this will change the global variable mutable
    global immutable1
    immutable1 = 'abc-CHANGED' # this will change the global variable immutable1 because global has been called
    immutable2 = '123-CHANGED' # this will not change the global immutable2 variable, because it's immutable and global has not bee declared

global唯一用于修改全局不可变变量的方法,还是可以在其他情况下使用它?

另一个例子:

>>> m={}
>>> i='a'
>>> 
>>> def change():
...     m['a'] = i
...     i = 'b'
... 
>>> print(m,i)
{} a
>>> change()
UnboundLocalError: local variable 'i' referenced before assignment

1 个答案:

答案 0 :(得分:4)

global与可变性无关。无论全局变量是指向可变对象还是可变对象,它都会更改名称作用域,以便您可以为该名称分配不同的值。

分配全局名称时,旧值可能是可变的,也可能不是可变的,新值也可以是可变的。

d = {}
e = 6

def change():
    global d, e
    d = 3
    e = []