对 Python3 中特定 class 的实例执行深层复制
Perform deep copy on assignment for instances of a specific class in Python3
我在 Python 中有一个 class,它比原始值多一点,例如 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" 运算符。相反,它将一个对象绑定到一个值。但是,您可以使用 copy
模块,如下所述:https://docs.python.org/3/library/copy.html.
我在 Python 中有一个 class,它比原始值多一点,例如 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" 运算符。相反,它将一个对象绑定到一个值。但是,您可以使用 copy
模块,如下所述:https://docs.python.org/3/library/copy.html.