I need my class to create new copy of object when referenced.
For example:
obj1 = MyClass(1,2)
obj2 = obj1
obj2.1st_att = 5
>>> print obj1
(5,2)
I want obj1 to remain unlinked to obj2
I need my class to create new copy of object when referenced.
For example:
obj1 = MyClass(1,2)
obj2 = obj1
obj2.1st_att = 5
>>> print obj1
(5,2)
I want obj1 to remain unlinked to obj2
You should copy object in cases like this.
from copy import copy
obj1 = MyClass(1,2)
obj2 = copy(obj1)
obj2.1st_att = 5
Or deepcopy if your class is complicated and has lots of references.
Python isn't making a copy of ints or floats every time you assign them to a different variable. The thing is that they're not mutable; there's nothing you could do to an int
that would change it, so however many variables you assign it to, you won't ever get any surprising behaviour.
With obj2.1st_att = 5
, you're explicitly modifying an attribute of an object. There's no analog operation to that for an int
. It is expected that this operation modifies the object, and that this change will be visible to anyone else who holds a reference to that object.
You should not try to work around that behaviour in any way, as that would break a lot of expectations and cause bugs or surprising behaviour in itself. It is good that making a copy of an object is an explicit action you need to take. Get used to it.