beMerry
beMerry

Reputation: 71

use == to check if two objects have the same value or not in python

The following is the code:

class foo:
   def __init__(self,p1,p2):
       self.a1 = p1
       self.a2 = p2

def main():
    o1=foo("lucy","jack")
    o2=foo('lucy','jack')
    print(o1==o2)
main()

I understand that o1 and o2 are different objects. What confuses me is that, they have the same value, right? And the "==" is used to check to see if two objects have the same value or not, right? Did I miss something here?

Upvotes: 0

Views: 1227

Answers (3)

Jonathan
Jonathan

Reputation: 303

If you want to define equal objects as objects with all the same instance variables, this is easier then writing code to test each variable:

class foo:
    def __init__(self,p1,p2):
        self.a1 = p1
        self.a2 = p2

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


def main():
    o1=foo("lucy","jack")
    o2=foo('lucy','jack')
    print(o1==o2)
main()

Upvotes: 1

Shadow
Shadow

Reputation: 9427

When python doesn't know how to compare objects - it checks to see if you're handling the same instance. This is the same as what the is operator does.

If you want to override how python compares object - you will need to define the __eq__ method in your class.

See the the docs for more information

Upvotes: 1

Sraw
Sraw

Reputation: 20214

You need to implement your custom __eq__:

class foo:
    def __init__(self,p1,p2):
        self.a1 = p1
        self.a2 = p2

    def __eq__(self, another):
        return self.a1 == another.a1 and self.a2 == another.a2   

def main():
    o1=foo("lucy","jack")
    o2=foo('lucy','jack')
    print(o1==o2)
main()

Upvotes: 1

Related Questions