【发布时间】:2019-04-18 14:29:17
【问题描述】:
我在 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 中没有原始类型。对于 Python 中的所有对象,赋值的语义完全相同。除非你想破解解释器内部,否则你不能这样做。再次注意
int和float对象不是原始的。它们是成熟的对象,它们根本不公开任何 mutator 方法。 -
为了说明比什么都没有是原始的:请注意,您可以在数字文字上调用方法,尽管这在
ints 上有点棘手,因为语法:1 .__add__(2) == 3,3.14.__str__()
标签: python python-3.x deep-copy