【问题标题】:Perform deep copy on assignment for instances of a specific class in Python3在 Python3 中对特定类的实例执行深度复制
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 2020-03-03
    • 2018-04-30
    • 2020-09-24
    • 2012-05-10
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    相关资源
    最近更新 更多