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

后端 未结 4 1929
日久生厌
日久生厌 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 17:54

    For an arbitrary object, the == operator will only return true if the two objects are the same object (i.e. if they refer to the same address in memory).

    To get more 'bespoke' behaviour, you'll want to override the rich comparison operators, in this case specifically __eq__. Try adding this to your class:

    def __eq__(self, other):
        if self.param == other.param \
        and self.param_2 == other.param_2 \
        and self.param_3 == other.param_3:
            return True
        else:
            return False
    

    (the comparison of all params could be neatened up here, but I've left them in for clarity).

    Note that if the parameters are themselves objects you've defined, those objects will have to define __eq__ in a similar way for this to work.

    Another point to note is that if you try to compare a FooBar object with another type of object in the way I've done above, python will try to access the param, param_2 and param_3 attributes of the other type of object which will throw an AttributeError. You'll probably want to check the object you're comparing with is an instance of FooBar with isinstance(other, FooBar) first. This is not done by default as there may be situations where you would like to return True for comparison between different types.

    See AJ's answer for a tidier way to simply compare all parameters that also shouldn't throw an attribute error.

    For more information on the rich comparison see the python docs.

提交回复
热议问题