我有一个Python类,它只是原始值,如int
或float
,见下文
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)
我希望它的行为与原始类型一样。因此,当一个赋值发生时,如上所述,该值被深度复制,所以我不必考虑在我做这样的分配的任何地方手动执行。
如您所见,我尝试重写__copy__
方法。不幸的是,这里没有调用这种方法。还有另一种方法可以覆盖吗?我很确定这可以用C ++完成。它也可以在Python中完成吗?
您不能覆盖=
中的Python
赋值运算符,因为它不是“复制”运算符。相反,它将对象绑定到值。但是,您可以使用copy
模块,如下所述:https://docs.python.org/3/library/copy.html。