according to my understanding, in python
, if i want to change/write the value of a global variable
in a function
, i should firstly and locally make a global
declaration of this global variable
in the function
, whereas if only access/read the value of this global variable
, it's no need to make the global
declaration, as like the below simple code, which works as expected:
# python3
global_var = 10
def read_global_var():
print(global_var) # the global var is successfully read without global declare
def write_global_var():
global global_var # global declare is must before write
global_var = 5
print(global_var)
read_global_var()
write_global_var()
print(global_var)
but when comes to the instance of python class, in a similiar usecase, i just found global
statement looks not necessary, which makes me confused, as in the following example:
# python3
class C:
def __init__(self):
self.x = 1.0
def read_global_instance():
print(global_instance.x)
def write_global_instance():
# global instance # this global declare is not nessesary, looks no different with or without this
global_instance.x = 3.0
# not like "global var", the "global instance" does not global declare before write
global_instance = C()
print(global_instance.x)
read_global_instance()
write_global_instance()
print(global_instance.x)
can i get any explanation about this inconsistent, at least to me, the two examples above are the same use-case.