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

Viewed 61
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
3 Answers

You can implement __eq__() for your class.

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

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

    def __eq__(self, other):
        return self.value == other


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

This is called "operator overloading" and it allows you to define custom behaviour for builtin operators (in this case the = operator).

Bear in mind that both operator precedence and associativity apply.

More on this in the Python documentation.

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

yes, as in comment mention you need to override the equals for the class

example:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class foo:
      def __init__(self, x=0,name=""):
            self.o=x
            self.name=name

      def __eq__(self, other):
             #compare here your fields 
             return self.name==other

if __name__ == "__main__":

    d1 = foo(1,"1")
    d2=foo(1,"2")
    print (d1=="1")

    print ("1"==d1)
Related