OrderedDict 子项的深层副本

Nik*_*Nik 4 python ordereddictionary

我已经尝试过deepcopyfromcopy模块。它适用于 OrderedDict 实例和 dict child 实例。但它不适用于 OrderedDict 子实例。这是一个演示:

from collections import OrderedDict
from copy import deepcopy

class Example2(dict):
    def __init__(self,l):
        dict.__init__(self,l)

class Example3(OrderedDict):
    def __init__(self,l):
        OrderedDict.__init__(self,l)

d1=OrderedDict([(1,1),(2,2)]) 
print(deepcopy(d1))           #OrderedDict([(1, 1), (2, 2)])

d2=Example2([(1,1),(2,2)])
print(deepcopy(d2))           #{1: 1, 2: 2}

d3=Example3([(1,1),(2,2)])
print(deepcopy(d3))
Run Code Online (Sandbox Code Playgroud)

前两个示例按预期工作,但最后一个因异常而崩溃:

TypeError: __init__() missing 1 required positional argument: 'l'
Run Code Online (Sandbox Code Playgroud)

所以问题是:这里的实际问题是什么,是否可以在deepcopy这种情况下使用该功能?

Joh*_*han 5

问题在于您的 Example3 类中的构造函数,deepcopy 将调用默认构造函数(无参数),但您尚未定义它,因此崩溃。如果您更改构造函数定义以使用列表的可选参数,它将起作用

像这样

class Example3(OrderedDict):
    def __init__(self, l = []):
        OrderedDict.__init__(self, l)
Run Code Online (Sandbox Code Playgroud)

然后

>>> d3 = Example3([(1, 1), (2, 2)])
>>> print(deepcopy(d3))
Example3([(1, 1), (2, 2)])
Run Code Online (Sandbox Code Playgroud)