Suppose I want to create my own version of an existing class. Let's pick the builtin float class. In this example, I'll create a float like class that do not raise an error when dividing by zero but instead returns the string 'inf' (Remember this is just an example. Avoiding division by zero error is not the main point of this question).
class myfloat(float):
def __truediv__(self, b):
if b == 0:
return 'inf'
else:
return myfloat(self.__float__() / b)
It works also when the division is coupled with int or float.
In[88]: a = myfloat(10)
In[89]: a / 2
Out[89]: 5.0
In[90]: a / 0
Out[90]: 'inf'
However, due to the inheritance from the float class, when I carry any other operation (i.e. method) the result will be a float. For example:
In[92]: b = myfloat(20)
In[93]: (a + b) / 0
ZeroDivisionError Traceback (most recent call last)
<ipython-input-6-f769cd843514> in <module>()
----> 1 (a + b) / 0
ZeroDivisionError: float division by zero
The addition method, still unaltered from the one inherited from the parent float class, obviously returns a float.
So my question: Is there a neat way to make all inherited methods in the child class to return a result which is in the child class, without the need to rewrite all methods? I'm thinking something like a decorator @myfloat
being automatically applied to all (applicable) inherited methods to convert their result from the type float
to the type myfloat
.