Is there a way to check if two object contain the same values in each of their variables in python?

后端 未结 4 1926
日久生厌
日久生厌 2020-12-14 17:29

How do I check if two instances of a

class FooBar(object):
    __init__(self, param):
        self.param = param
        self.param_2 = self.function_2(param         


        
4条回答
  •  情话喂你
    2020-12-14 18:04

    According to Learning Python by Lutz, the "==" operator tests value equivalence, comparing all nested objects recursively. The "is" operator tests whether two objects are the same object, i.e. of the same address in memory (same pointer value). Except for cache/reuse of small integers and simple strings, two objects such as x = [1,2] and y = [1,2] are equal "==" in value, but y "is" x returns false. Same true with two floats x = 3.567 and y = 3.567. This means their addresses are different, or in other words, hex(id(x)) != hex(id(y)).

    For class object, we have to override the method __eq__() to make two class A objects like x = A(1,[2,3]) and y = A(1,[2,3]) "==" in content. By default, class object "==" resorts to comparing id only and id(x) != id(y) in this case, so x != y. In summary, if x "is" y, then x == y, but opposite is not true.

提交回复
热议问题