Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality of objects in Python [duplicate]

I have a class MyClass, which contains two member variables foo and bar:

class MyClass:
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

I have two instances of this class, each of which has identical values for foo and bar:

x = MyClass('foo', 'bar')
y = MyClass('foo', 'bar')

However, when I compare them for equality, Python returns False:

>>> x == y
False

How can I make python consider these two objects equal?

like image 402
Ivy Avatar asked Apr 27 '12 11:04

Ivy


People also ask

What is object equality in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

How do you duplicate an object in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object. Let's take an example where we create a list named old_list and pass an object reference to new_list using = operator.

What is the difference between identical and equal objects in Python?

The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.

What is the == in Python?

== is the equality operator. It is used in true/false expressions to check whether one value is equal to another one. For example, (2 + 2) == 5 evaluates to false, since 2 + 2 = 4, and 4 is not equal to 5. The equality operator doens't set any value, it only checks whether two values are equal.


1 Answers

you have to tell python how exactly you want equality be defined. do so by defining a special method __eq__ like this:

def __eq__(self, other):
    return self.attrfoo == other.attrfoo # change that to your needs

the __cmp__(self, other) is the "old" style to compare instances of classes, and only used when there is no rich comparison special method found. read up on them here: http://docs.python.org/release/2.7/reference/datamodel.html#specialnames

like image 89
ch3ka Avatar answered Sep 20 '22 05:09

ch3ka