全局可变与不可变

2024-10-03 13:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是对可变对象和不可变对象上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

Tags: the对象defthischangevariableglobalwill
1条回答
网友
1楼 · 发布于 2024-10-03 13:20:48

global与可变性无关。它会更改名称范围,无论全局引用的是可变对象还是不可变对象,以便您可以为名称指定不同的值。你知道吗

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

d = {}
e = 6

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

相关问题 更多 >