为什么包含实例的字典的深层副本的结果与包含列表的另一个字典的深层副本不同?
Why the results of a deep copy of a dictionary, containing instances, is different from a deep copy of another dictionary, which contains lists?
调试作业的时候,发现需要用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
的副本,我应该怎么做?
问题是在 python 中,默认情况下,对象的副本与原始对象不相等,即使它们是 "same",例如:
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
调试作业的时候,发现需要用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
的副本,我应该怎么做?
问题是在 python 中,默认情况下,对象的副本与原始对象不相等,即使它们是 "same",例如:
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