在Python3中为特定类的实例分配执行深层复制

问题描述 投票:1回答:1

我有一个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 python-3.x deep-copy
1个回答
1
投票

您不能覆盖=中的Python赋值运算符,因为它不是“复制”运算符。相反,它将对象绑定到值。但是,您可以使用copy模块,如下所述:https://docs.python.org/3/library/copy.html

© www.soinside.com 2019 - 2024. All rights reserved.