2015-03-02 66 views
3

我已经从copy模块尝试过deepcopy。它适用于OrderedDict实例和dict子实例。但它不适用于OrderedDict子实例。这里是一个演示: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)) 

一两个例子如预期,但与异常的最后一个崩溃:

TypeError: __init__() missing 1 required positional argument: 'l' 

所以,问题是:究竟是这里的问题,是有可能完全可以使用deepcopy函数来处理这种情况?

+0

您需要通过它来itterate和deepcopy的每个元素的自己 – Vajura 2015-03-02 06:05:13

回答

4

问题是你的Example3类中的构造函数,deepcopy会调用默认的构造函数(没有参数),但你没有定义这个,因此崩溃。如果你改变你的构造函数定义中使用可选参数的列表,而不是,它会工作

像这样

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

然后

>>> d3 = Example3([(1, 1), (2, 2)]) 
>>> print(deepcopy(d3)) 
Example3([(1, 1), (2, 2)]) 
+1

谢谢你的回答。虽然,我应该承认,我不完全明白为什么Example2有效,而Example3不能。 – Nik 2015-03-02 07:20:34

+0

好点!不能找到它的证据,但怀疑它是由于字典中的构建,所以deepcopy可以处理它不同 – Johan 2015-03-02 08:12:15

+0

只要提及我在类似的情况下得到了同样的错误,虽然我用dict.copy()而不是deepcopy的。 – paulochf 2017-04-04 23:53:02