avamsi avamsi - 11 days ago 6
Python Question

__eq__ on super objects

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__'

Answer

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.