2
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
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
C3pLus
  • 93
  • 6

3 Answers3

1

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.

Teymour
  • 1,832
  • 1
  • 13
  • 34
1

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
Michail Highkhan
  • 517
  • 6
  • 18
1

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)
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97