Reputation: 99
I have a class in Python which is little more than the primitive values, like int
or float
, see below
class Entry:
def __init__(self, value, timestamp):
self.value = value
self.timestamp = timestamp
def __str__(self):
return"[v= {}, ts= {}]".format(self.value, self.timestamp)
def __hash__(self):
return hash(self.timestamp)
def __eq__(self, other):
return self.timestamp == other.timestamp
def __le__(self, other):
return self.timestamp <= other.timestamp
def __lt__(self, other):
return self.timestamp < other.timestamp
def __ge__(self, other):
return self.timestamp >= other.timestamp
def __gt__(self, other):
return self.timestamp > other.timestamp
def __copy__(self):
new_entry = Entry(deepcopy(self.value), self.timestamp)
print("hi")
return new_entry
e1 = Entry("some name", 10)
e2 = e1
e2.timestamp = 20
print(e1)
I want it to behave just like the primitive types as well. So when an assignment occurs, like above, the value is deep-copied, so I don't have to think about doing it manually everywhere I do assigment like this.
As you can see, I tried overriding the __copy__
method. Unfortunely that method isn't called here. Is there another method to override? I'm pretty sure this can be accomplished in C++. Can it be done in Python too?
Upvotes: 1
Views: 110
Reputation: 311
You can't override the =
assignment operator in Python
, because it isn't a "copy" operator. Instead it binds an object to a value. You can, however, use the copy
module, as described here: https://docs.python.org/3/library/copy.html.
Upvotes: 1