简体   繁体   English

全局可变与不可变

[英]Global on mutable vs immutable

Is the following a correct understanding of global on mutable vs immutable objects?以下是对可变对象与不可变对象的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

Is the only usage of global to modify a global immutable variable, or can it ever be used in other situations? global是修改全局不可变变量的唯一用途,还是可以在其他情况下使用?

Another example:另一个例子:

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

global has nothing to do with mutability. global与可变性无关。 It changes the scope of a name , whether the global refers to a mutable or immutable object, so that you can assign a different value to the name.它改变了名称scope ,无论全局是指可变的还是不可变的 object,以便您可以为名称分配不同的值。

When assigning to a global name, the old value may or may not have been mutable, and the new value can be either as well.分配给全局名称时,旧值可能是可变的,也可能不是可变的,新值也可以是可变的。

d = {}
e = 6

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM