0

With my class if i make an instance of it and then create a copy using the equals operator, any changes made to the copy are inherited by the original instance. An example:

class Points():
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
    def __str__(self):
        return "(% s, % s, % s)" % (self.x, self.y, self.z)
    def __repr__(self):
        return "(% s, % s, % s)" % (self.x, self.y, self.z)

Instance1 = Points(1,2,3)
Instance2 = Instance1 
Instance2.x = 3 
print(Instance1)

Output:

(3, 2, 3)

I simply wanted to know why this was happening and if their was anyway to avoid it without using an external variable

I tried using an external variable to save the value that i would change in Instance2 which worked, I also found a post about the same issue happening with lists and how reassigning like this is actually just giving it a new name but this returned an error, which made even less sense to me.

class Points():
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
    def __str__(self):
        return "(% s, % s, % s)" % (self.x, self.y, self.z)
    def __repr__(self):
        return "(% s, % s, % s)" % (self.x, self.y, self.z)

Instance1 = Points(1,2,3)
Instance2 = Points(3,2,3)
Instance2 = Points(Instance1) 
Instance2.x = 3 
print(Instance1)

Output:

Traceback (most recent call last):
  File "<string>", line 13, in <module>
TypeError: Points.__init__() missing 2 required positional arguments: 'y' and 'z'

I also found another question which related to mine but they were using lists as well.

Jamsta
  • 1
  • 5
    That isn't a second instance. It's the same instance. Assignment never copies. – Axe319 Jan 19 '23 at 19:41
  • `Instance2 = Instance1` creates a second ***reference*** to the same instance – PM 77-1 Jan 19 '23 at 19:42
  • `Instance2 = Points(Instance1.x, Instance1.y, Instance1.z)` should work in your second example. Indeed, Points() requires three input arguments, not one. For more general purposes, see the "This question already has answers here:" link above. – Convexity Aug 16 '23 at 13:20

0 Answers0