2015-12-21 62 views
0

在調試我的作業時,我意識到我需要使用deepcopy複製字典。爲什麼包含實例的字典的深層副本的結果與另一個包含列表的字典的深層副本不同?

我預計deepcopy給我類似的結果(用列表的字典打交道時,這是真的):

import copy 

dict3 = {1 : [1,2,3], 2 : [1,2]}  
dict4 = copy.deepcopy(dict3)   

print dict3       # {1: [1, 2, 3], 2: [1, 2]} 
print dict4       # {1: [1, 2, 3], 2: [1, 2]} 

print dict3 == dict4    # True 

然而,我發現這樣的:

import copy 

class Fruit(object): 
    def __init__(self, name, color): 
     self.name = name 
     self.color = color 

    def __repr__(self): 
     return self.color 

# Building dict1 
dict1 = {} 
dict1['apple'] = Fruit('apple', 'red') 
dict1['banana'] = Fruit('banana', 'yellow') 

# Deep copy dict1 and assign it to dict2 
dict2 = copy.deepcopy(dict1) 

print dict1   # {'apple': red, 'banana': yellow} 
print dict2   # {'apple': red, 'banana': yellow} 

print dict1 == dict2 # False 

如果我想要一個在最後的print聲明中給我一個True的副本,我該怎麼辦?

+3

您還沒有實現在''__eq__' ... Fruit' – jonrsharpe

+0

@jonrsharpe我不知道,哈哈。非常感謝! –

回答

1

的問題是,在Python,默認情況下,一個對象的副本並不比等於原始,即使他們是「相同的」,例如:

class Fruit(object): 
    def __init__(self, name, color): 
     self.name = name 
     self.color = color 

    def __repr__(self): 
     return self.color 

print Fruit("apple", "red") == Fruit("apple", "red") 
# False 

爲了解決這個問題,你需要告訴Python的Fruit類型的對象應比較,例如:

class Fruit(object): 
    def __init__(self, name, color): 
     self.name = name 
     self.color = color 

    def __repr__(self): 
     return self.color 

    def __eq__(self, other): 
     try: 
      if (self.name == other.name) and (self.color == other.color): 
       return True 
      else: 
       return False 
     except AttributeError: 
      return False 
+0

非常感謝! –

+1

只需添加一個鏈接到內置的比較規則。很高興知道Python可以比較什麼。對於其他所有你提供的__eq__,如Bi Rico的答案所示。 https://docs.python.org/3/reference/expressions.html#value-comparisons – VPfB