Search code examples
pythonpython-2.7inheritanceoperator-overloadingcomparison-operators

Accessing original int comparison from int-derived class with overloaded comparison operator


I have an int-derived class with overloaded comparison operator.

In the body of the overloaded methods I need to use the original operator.

The toy example:

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

works fine with Python 3.3+, but fails with Python 2.7 with exception AttributeError: 'super' object has no attribute '__eq__'.

I can think about several walkarrounds, which I found not very clean:

return int(self) == other

requires creation of a new int object just to compare it, while

try:
    return super(Derived, self).__eq__(other)
except AttributeError:
    return super(Derived, self).__cmp__(other) == 0

splits the control flow based on the Python version, which I find terribly messy (so is inspecting the Python version explicitly).

How can I access the original integer comparison in an elegant way working with Python 2.7 and 3.3+?


Solution

  • I believe that you should define the __eq__ in the int before defining the class. For example:

    int = 5
    def int.__eq__(self, other):
        return self.real == other
    IntDerived = Derived(int)
    

    This should give the super class an __eq__ attribute.


    EDITED


    The main idea worked, but it has been brought to my attention that the code isn't working. So: improved code:

    class Derived(int):
        def __eq__(self, other):
            return self.real == other
    
    Int = 5
    D = Derived(Int)
    D.__eq__(4) #Output: False
    D.__eq__(5) #Output: True