3

Following piece of code works fine in Python 3 (3.5.2) but raises an AttributeError: 'super' object has no attribute '__eq__' in Python 2 (2.7.12)

class Derived(int):

    def __eq__(self, other):
        return super(Derived, self).__eq__(other)


a, b = Derived(1024), Derived(1729)
print(a == b)

Python 3 behaviour is expected. I'm trying to understand why it doesn't work in Python 2.

Please note that this question is not a duplicate of 'super' object has no attribute '__eq__'

avamsi
  • 389
  • 3
  • 16
  • 2
    Because in Python 2 `int` doesn't have rich comparison operators (see [here](http://stackoverflow.com/questions/10809932/python-why-does-the-int-class-not-have-rich-comparison-operators-like-lt)). Python 3 implements rich comparison operators as `__cmp__` was depracated. – Eli Sadoff Nov 28 '16 at 16:57

1 Answers1

4

What is happening here is that the super class for Derived is int. In Python 2, int does not implement rich comparison operators like __lt__, __gt__, or __eq__ as it uses __cmp__ instead. However, __cmp__ is not supported in Python 3, so int implements rich comparison operators like __lt__, __gt__, and __eq__ in Python 3. So, in Derived in Python 2, super.__eq__ does not exist because int.__eq__ does not exist in Python 2.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
  • I kind of assumed `int` implements `__eq__` from this `>>> int.__eq__ ` but now I tried `int.__eq__(1, 2)` and got an error. `int.__eq__(0)` returns `NotImplemented` Can you expand on how all this works? – avamsi Nov 28 '16 at 17:07
  • 2
    In python 2 `int.__eq__` is comparing the `int` class to another class, not comparing `int`s. So `int.__eq__(int)` will be true, but `int.__eq__(float)` will be false. – Eli Sadoff Nov 28 '16 at 17:09
  • Makes sense. Thanks for the clarification. – avamsi Nov 28 '16 at 17:11
  • No worries. Python 2 has some weird features in it related to this. Python 3 tried to standardize a lot better. – Eli Sadoff Nov 28 '16 at 17:11