Access to source comparison with int-derived class with overloaded comparison operator

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

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

Toy example:

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

works great with Python 3.3+, but doesn't work with Python 2.7 with the exception of AttributeError: 'super' object has no attribute '__eq__' .

I can think of a few walkarrounds that I found not very clean:

 return int(self) == other 

you need to create a new int object only to compare it, and

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

shares a control flow based on the version of Python that I find terribly messy (so I explicitly check the version of Python).

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

+5
source share
4 answers

I believe that before defining a class, you should define __eq__ in int . For instance:

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

This should give the super a __eq__ .


edited


The basic idea worked, but I was informed that the code was not 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 
0
source

Python 2 and 3 are significantly different from each other, so I think you should bite the bullet and check the versions. This can only be expected if you are trying to write code that works on both (sooner or later in my experience you will find something that you need to fix). To avoid any performance impact, you can do something like:

 from six import PY2 class Derived(int): if PY2: def __eq__(self, other): return super(Derived, self).__cmp__(other) == 0 else: def __eq__(self, other): return super(Derived, self).__eq__(other) 

What would i do. If I really wanted to subclass int ...

If you really do not want this, perhaps you could try:

 class Derived(int): def __eq__(self, other): return (self ^ other) == 0 

Obviously, if you care about performance, you will have to do some profiling with the rest of your code and find out if any of them are much worse ...

+2
source

Both versions implement the __xor__ method, you can try the following:

 class Derived(int): def __eq__(self, other): return not super(Derived, self).__xor__(other) 
+1
source

using hasattr avoids creating a new int object by catching an exception or explicitly checking the version of Python.

The code below works on both Python 2.7 and 3.3+:

 class Derived(int): def __eq__(self, other): return super(Derived, self).__cmp__(other) == 0 if hasattr(Derived, "__cmp__") else super(Derived, self).__eq__(other) 
0
source

Source: https://habr.com/ru/post/1260459/


All Articles