我在 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
中的 =
赋值运算符,因为它不是“复制”运算符。相反,它将一个对象绑定(bind)到一个值。但是,您可以使用 copy
模块,如下所述:https://docs.python.org/3/library/copy.html .
关于python - 对 Python3 中特定类的实例进行赋值深复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748205/