Comparing two objects

后端 未结 4 1764
误落风尘
误落风尘 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:47

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

    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.

提交回复
热议问题