Search code examples
pythoncomparison

Is it possible to make Instance == string/int/float or any datatype to be True in python?


class Element:
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def __repr__(self):
        return repr(self.value)


example = Element("project", "some project") 

example == "some project"  # False

Is there a way to make above statement True rather than

example.value == "some project" # True

Solution

  • You can try overloading __eq__ and __ne__ operators in your class.

    class Element:
        def __init__(self, val):
            self.val = val
        def __eq__(self, other):
            return self.val == other
    
    f = Element("some project")
    f == "some project" # True