Comparing two objects

后端 未结 4 1751
误落风尘
误落风尘 2021-01-01 16:23

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?

4条回答
  •  失恋的感觉
    2021-01-01 16:49

    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
    

提交回复
热议问题