Attribute update problem after python instantiation

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!


because you directly modified the entire reference of self.x . The operation of self.x + = 1 is to change the pointing to of self.x from the original value to another value, rather than changing the value it points to to change to another value, while self.z still stores the old value pointed to by self.x , of course it will not be updated. To achieve the similar effect you want, try

a = []
b = []
c = [ a, b ]
print(c)
a.append(1)
b.append(2)
print(c)

has nothing to do with instantiation.

the above code modifies the values that a and b point to, rather than modifying the entire reference to point to the new value. That is to say, the directions of the modified a and b have not changed (while self.x + = 1 modified the self.x direction), so the two elements of c can still find the values consistent with the current a and b through their references

.

wrap the function as a property with @ property

python3

>>> class A():
    def __init__(self):
        self.x = 0
        self.y = 0
        
    @property -sharp 
    def z(self):
        return [self.x, self.y]

    def add_one(self):
        self.x += 1

        
>>> a=A()
>>> a.add_one()
>>> a.x
1
>>> a.z
[1, 0]
>>> 
Menu