How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this?

后端 未结 2 354
春和景丽
春和景丽 2020-12-01 00:39

I need to create a \'container\' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objec

相关标签:
2条回答
  • 2020-12-01 01:24

    Yes, you need a __hash__()-method AND the comparing-operator which you already provided.

    class Item(object):
        def __init__(self, foo, bar):
            self.foo = foo
            self.bar = bar
        def __repr__(self):
            return "Item(%s, %s)" % (self.foo, self.bar)
        def __eq__(self, other):
            if isinstance(other, Item):
                return ((self.foo == other.foo) and (self.bar == other.bar))
            else:
                return False
        def __ne__(self, other):
            return (not self.__eq__(other))
        def __hash__(self):
            return hash(self.__repr__())
    
    0 讨论(0)
  • 2020-12-01 01:25

    I am afraid you will have to provide a __hash__() method. But you can code it the way, that it does not depend on the mutable attributes of your Item.

    0 讨论(0)
提交回复
热议问题