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?
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 .
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.
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.
== 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With