Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 265
avamsi Avatar asked Dec 05 '25 11:12

avamsi


1 Answers

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.

like image 141
Eli Sadoff Avatar answered Dec 06 '25 23:12

Eli Sadoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!