Python不认为等价对象是等价的

2024-04-20 00:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在酸洗、压缩和保存python对象。我希望能够再次检查我保存的对象是否与解压缩和删除后返回的对象完全相同。我以为我的代码中有一个错误,但是当我把问题归结为一个可重复的例子时,我发现python并不认为在两个不同的时间点创建的两个看起来完全相同的对象是相等的。下面是一个可复制的例子:

class fubar(object):
    pass

print(fubar() == fubar())
#False

为什么python认为这两个对象不相等?检查两个对象是否完全相同的最python方法是什么?


Tags: 对象方法代码falseobject错误时间pass
3条回答

Python中默认的相等比较是检查标识(即两个对象是同一个对象)。在

根据Python Library Reference

Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method or the __cmp__() method.

要创建您自己的等价定义,您需要定义一个方法。以下是一种方法:

class fubar(object):

    def __eq__(self, other):
        'Fubar objects are considered equal if they have the same contents'
        if type(self) != type(other):
            return NotImplemented
        return vars(self) == vars(other)

NotImplemented的返回值表示fubar不知道如何进行比较,并给其他对象一个进行比较的机会。在

Python Language Reference对未实现的有如下说明:

This type has a single value. There is a single object with this value. This object is accessed through the built-in name NotImplemented. Numeric methods and rich comparison methods may return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) Its truth value is true.

你应该看看this答案。基本上,定义您的__eq__方法来比较to对象的self.__dict__,这将返回一个包含对象属性的字典。在

它们不是同一个物体。例如,检查id(fubar())id(fubar())的值。如果要重新定义相等的工作方式,则需要实现your own equality method

class fubar(object):

    def __eq__(self, other):
        return True # make this more complex

self和{}相等时,此方法应返回True,否则返回{}。在

相关问题 更多 >