【问题标题】:Why the results of a deep copy of a dictionary, containing instances, is different from a deep copy of another dictionary, which contains lists?为什么包含实例的字典的深层副本的结果与另一个包含列表的字典的深层副本不同?
【发布时间】:2016-03-28 03:33:38
【问题描述】:

在调试作业时,我意识到我需要使用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 的副本,我应该怎么做?

【问题讨论】:

  • 你还没有在Fruit上实现__eq__...
  • @jonrsharpe 我不知道,哈哈。非常感谢!

标签: python python-2.7 class dictionary deep-copy


【解决方案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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2022-12-13
相关资源
最近更新 更多