Python 比较两个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3550336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:41:36  来源:igfitidea点击:

Comparing two objects

python

提问by iman453

Is there any way to check if two objects have the same values, other than to iterate through their attributes and manually compare their values?

除了遍历它们的属性并手动比较它们的值之外,有什么方法可以检查两个对象是否具有相同的值?

采纳答案by Joe Kington

@Joe Kington's solutions works if there is a __dict__(some objects, including builtins, don't have one) and __eq__works for all values of both dicts (a badly written __eq__mayraise exceptions etc). But it is horribly unpythonic. It doesn't even handle nominal subtypes properly... much less structural subtypes (i.e. types that you can use in place/for duck-typing). Do not do this.

@Joe Kington 的解决方案适用于__dict__(某些对象,包括内置__eq__函数,没有)并且适用于两个字典的所有值(写得不好的可能__eq__引发异常等)。但它非常不符合 Python 标准。它甚至不能正确处理名义子类型……更不用说结构子类型(即您可以就地使用/用于鸭子类型的类型)。不要这样做。

But usually you're better off with a hand-tailored __eq__method that only compares some attributes that are significant. E.g. Rational should only compare numerator and denominator, nothing more.

但通常你最好使用手工定制的__eq__方法,只比较一些重要的属性。例如,Rational 应该只比较分子和分母,仅此而已。

回答by Joe Kington

object1.__dict__ == object2.__dict__Should be all you need, I think...

object1.__dict__ == object2.__dict__应该是你所需要的,我想......

Edit: vars(object1) == vars(object2)is perhaps a bit more pythonic, though @delnan makes a valid point about objects (e.g. ints) that don't have a __dict__. I disagree that a custom __eq__is a better approach for simple cases, though... Sometimes it's not worth the effort to go beyond quick and dirty, if quick and dirty perfectly does what you need, i.m.h.o.

编辑:vars(object1) == vars(object2)可能更像 pythonic,尽管 @delnan 对int没有__dict__. 我不同意__eq__对于简单的情况,自定义是一种更好的方法,但是......有时,超越快速和肮脏的努力是不值得的,如果快速和肮脏完美地满足您的需求,恕我直言

回答by habnabit

To expound on delnan's answer:

阐述德尔南的回答:

_NOTFOUND = object()

class Rational(object):
    def __eq__(self, other):
        for attr in ['numerator', 'denominator']:
            v1, v2 = [getattr(obj, attr, _NOTFOUND) for obj in [self, other]]
            if v1 is _NOTFOUND or v2 is _NOTFOUND:
                return False
            elif v1 != v2:
                return False
        return True

回答by John La Rooy

You can compare namedtupledirectly.
Otherwise you have to define either your own rich comparisons __eq__and possibly __ne__
or your own __cmp__

您可以直接比较namedtuple
否则,您必须定义自己的丰富比较__eq__以及可能__ne__
或您自己的__cmp__

see the datamodelfor more info

有关更多信息,请参阅数据模型