2015-03-02 83 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