亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python中,如何在__deepcopy __()的實現中調用copy.deepcopy?

在Python中,如何在__deepcopy __()的實現中調用copy.deepcopy?

料青山看我應如是 2021-03-30 08:47:54
我想創建一個類,該類可以提供不會被深度復制的屬性列表copy.deepcopy()。例如這樣的例子:class CustomDeepcopy(object):    a = SomeSimpleObject()    b = SomeBigObject()    def dont_deepcopy(self):        return ['b']    def __deepcopy__(self,memo):        #Somehow call copy.deepcopy(self) and have it          #deepcopy self.a but not self.b        #        #For example, this *almost* works,         for attr in self.dont_deepcopy():            val = getattr(self,attr,None)            if val is not None:                 memo[id(val)]=val        return copy.deepcopy(self,memo)問題是我認為我不能copy.deepcopy()從內部調用,__deepcopy__()因為這會導致無限遞歸(因為copy.deepcopy()首先檢查我的對象是否具有__deepcopy__()方法)。有什么辦法可以做到嗎?
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

任何時候你實現一個特殊的方法(如__getattr__,__deepcopy__,__str__,等),您可能需要上浮MRO超或使用原來的某個子集。


我尚不清楚您是如何記憶屬性的,但我將簡化您的示例。假設您始終使用相同的a(并且它是不可變的,不需要復制),但是否則,您想要復制b。(你可以通過a和b直接構造,使一個新的對象。


class CustomDeepcopy(object):

    def __init__(self, a=None, b=None):

        if a:

            self.a = a

        if b:

            self.b = b


    a = SomeSimpleObject()

    b = SomeBigObject()


    @property

    def dont_deepcopy(self):

        return ['b']

    @property

    def deepcopy_attributes(self):

        return ['a']


    def __deepcopy__(self,memo):

        new_kwargs = dict((k, getattr(self, attr, None)) for attr in self.dont_deepcopy)

        for attr in self.deepcopy_attributes:

            new_kwargs[attr] = copy.deepcopy(getattr(self, attr, None))

        return self.__class__(**new_kwargs)


查看完整回答
反對 回復 2021-04-05
?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

copy.deepcopy僅__deepcopy__在存在該方法的情況下才會調用-我們可以通過保存__deepcopy__,調用copy.deepcopy(...)的值,__deepcopy__然后在返回結果之前恢復的值來避免這種情況:


class CustomDeepcopy(object):


    a = SomeSimpleObject()

    b = SomeBigObject()


    def dont_deepcopy(self):

        return ['b']


    def __deepcopy__(self,memo):

        for attr in self.dont_deepcopy():

            val = getattr(self,attr,None)

            if val is not None:

                 memo[id(val)]=val

        deepcopy_method = self.__deepcopy__

        self.__deepcopy__ = None

        result = copy.deepcopy(self,memo)

        self.__deepcopy__ = deepcopy_method

        return result


查看完整回答
反對 回復 2021-04-05
  • 2 回答
  • 0 關注
  • 822 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號