以下是对可变对象和不可变对象上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
global
与可变性无关。它会更改名称的范围,无论全局引用的是可变对象还是不可变对象,以便您可以为名称指定不同的值。你知道吗分配给全局名称时,旧值可能是可变的,也可能不是可变的,新值也可以是可变的。你知道吗
相关问题 更多 >
编程相关推荐