簡體   English   中英

將自定義(深層)復制邏輯添加到python類的正確方法

[英]correct way to add custom (deep) copying logic to a python class

我正在實現一個提供一些嵌套數據結構的python類。 我想補充通過復制支持copy.copy()通過和深拷貝copy.deepcopy()其中,作為用於復制模塊文檔描述,涉及編寫__copy__()__deepcopy__特殊的方法。

我知道如何教我的班級自己復制,但我想避免在新實例上通過__init__() ,因為__init__()做了我的復制邏輯不想要(或不需要)做的事情。

我最終得到的是這種方法,它按預期工作:

def __copy__(self):
    cls = type(self)
    obj = cls.__new__(cls)
    # custom copying logic that populates obj goes here
    return obj

我的問題是:調用cls.__new__(cls)正確的方法是__copy__()實現想要跳過__init__()的副本? 還是有一種我忽略的“pythonic”方法?

我不知道這是否更像pythonic,但你可以使用旗幟。

from collections import Mapping
from copy import copy, deepcopy


class CustomDict(dict, Mapping):
    _run_setup = True

    def __init__(self, *args, **kwargs):
        self._dict = dict(*args, **kwargs)
        if args and isinstance(args[0], CustomDict):
            self._run_setup = args[0]._run_setup
        if self._run_setup:
            print("Doing some setup stuff")
        else:
            try:
                print("Avoiding some setup stuff")
            finally:
                self._run_setup = True

    def __getitem__(self, key):
        return self._dict[key]

    def __iter__(self):
        return iter(self._dict)

    def __len__(self):
        return len(self._dict)

    def __copy__(self):
        self._run_setup = False
        try:
            copied_custom_dict = CustomDict(self)
        finally:
            self._run_setup = True
        return copied_custom_dict

在上面的__init__ ,只有在_run_setup = True才會完成條件設置。 避免這種情況的唯一方法是調用CustomDict ,第一個參數是_run_setup = False的自身實例。 這樣,很容易以不同的方法翻轉設置開關。

try...finally塊看起來很笨重但是這是一種確保每個方法以_run_setup = True開始和結束的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM