Comparing two objects

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

    @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.

    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.

提交回复
热议问题