python - 对 Python3 中特定类的实例进行赋值深复制

标签 python python-3.x deep-copy

我在 Python 中有一个类,它只不过是原始值,例如 intfloat,见下文

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/

相关文章:

python - 在Win7中安装qPython

python - sklearn 分类指标 auc 返回 ValueError

python - 构建 pygdal : Unknown distribution option: 'use_2to3_fixers' and 'use_2to3_exclude_fixers' 时出错

c# - 使用 ProtoBuf-net 反序列化派生类型(字典)未正确设置对象字段

c++ - 如何在 C++ 中同时使用默认和自定义复制构造函数?

组合组合时的 Python 记录频率

python - 如何设置manim渲染的图片/视频的大小?

python-3.x - Pandas - 查找在每个类(class)组中显示的唯一值

c# - 缓存对象的高效克隆

python 2.5 : how to convert float to hex?