I have just come into contact with Python
, and currently use python 3.6
. I have encountered some problems about class attributes. The code is as follows:
class A():
def __init__(self):
self.x = 0
self.y = 0
self.z = [self.x, self.y]
def add_one(self):
self.x += 1
-sharp self.z = [self.x, self.y]
a = A()
a.add_one()
print(a.x) -sharp 1
print(a.z) -sharp [0, 0]
the problem is as follows:
suppose there is no self.z = [self.x, self.y]
code in the add_one
method, you can find that although x
is updated, z
is not updated with the update of x
. Why can you update it only if you add this code manually?
is there any other easier way to update attributes? Because it is troublesome to update this kind of code at present, adding an update method requires all the updated properties to be updated manually
would like to have an elder who can give us some advice. If there is any improper expression, please forgive me!