Is the following a correct understanding of global
on mutable vs immutable objects?
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?
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. 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.
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 = []
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.