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.