Will
Will

Reputation: 4528

How does object.__eq__ have access to scope of method that calls it?

If I define an object in Python 2.7 like so:

class C(object):
    def __eq__(self, other):
        return object.__eq__(other)

equality works as one might desire:

In [2]: c = C()

In [3]: d = c

In [4]: d == c
Out[4]: True

In [5]: c == d
Out[5]: True

In [6]: C() == C()
Out[6]: False

However, when I call object.__eq__(other), I am not passing self at all, so where is it getting it from?

Upvotes: 1

Views: 51

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124090

It doesn't have access to self, no, and just returns the NotImplemented singleton:

>>> object.__eq__(None)
NotImplemented

because object.__eq__ is bound to the object type. Only object itself, if passed in, will produce a True result:

>>> object.__eq__(object)
True

It is used to test if classes are equal, not instances.

By extension, your class will return NotImplemented unless you pass in object:

>>> C().__eq__(None)
NotImplemented
>>> C().__eq__(object)
True
>>> C() == object
True

Python then asks the other object to do the equality test, and if that too returns NotImplemented an identity test is used instead.

So in the end, you could just as well have removed the __eq__ method as it does nothing but create some extra work that leads to nothing. :-)

Upvotes: 3

Related Questions