深度复制特定属性

时间:2018-09-08 13:24:46

标签: python oop copy

有没有一种方法可以覆盖类的__copy__方法,使得仅复制 some 属性作为参考,而其他属性真的已复制

为弄清我的意思,这是我对如何实现的猜测。考虑类Spam

class Spam:
    def __init__(self, val=0, val2=0):
        self.eggs = []
        self.foo = []
        self.val = val
        self.val2 = val2

假设我们要确保在对copy.copy对象调用Spam(即浅表副本)时,其eggs属性是深度复制放入新对象(这样,对原始对象属性的更改不会改变副本的eggs属性)。 “那么为什么不deepcopy整个对象呢?” –因为与eggs不同,我们希望将foo属性复制为 reference (以便所有副本都可以看到更改)。

那么,以下方法是否有效?

    to_be_copied = ['eggs']  # States which attributes are to be copied

    def __copy__(self):
        copy_ = Spam()

        for attr in self.__dict__:
            if attr in Spam.to_be_copied:
                # Make an actual copy of the attribute
                copy_.__dict__[attr] = copy.copy(self.__dict__[attr])  
            else:
                # Copy reference
                copy_.__dict__[attr] = self.__dict__[attr]

        return copy_

1 个答案:

答案 0 :(得分:1)

它看起来很有效,但是当存在很多属性时,将set设为to_be_copied会使操作更快。

还可以像下面这样用三元表达式+列表理解来缩短

to_be_copied = {'eggs'}  # States which attributes are to be copied

def __copy__(self):
    copy_ = Spam()
    copy_.__dict__ = {attr:copy.copy(self.__dict__[attr]) if attr in Spam.to_be_copied else self.__dict__[attr] for attr in self.__dict__}
    return copy_

覆盖__copy__ dunder方法的缺点是它不符合最不令人惊讶的原则:copy.copy的用户在处理诸如{{1} },您将提供自定义副本。

也许最好定义一个list函数(正确记录)

相关问题