I'm trying to create a class MyFloat that is very similar to float but has a value method and a few other methods. I also need instances of this class to interact with real floats and be "sticky" in the sense that type(MyFloat(5) + 4) is MyFloat and not float.
So this is what I have so far:
class MyFloat(numbers.Real):
def __init__(self, value):
self._value = float(value)
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = float(value)
def __float__(self):
return self.value
but now I have to implement a ton of other methods in order to satisfy the abstract base class numbers.Real and also my requirement that this "acts" like a float. The issue is that a) there's a ton of these methods (__add__, __trunc__, __floor__, __round__, __floordiv__... I think 24 in total) and b) they all kinda follow the same pattern. That is, for any method, I probably just want:
def __method__(self):
return MyFloat(float.__method__(float(self))
or
def __method__(self, other):
return MyFloat(float.__method__(float(self), float(other)))
Is there a way to do what I want without manually implementing every math method (and repeating a ton of code)?
Keep in mind that float.__method__ doesn't actually exist for every method. For example, float.__floor__ doesn't exist, but I still need to implement MyFloat.__floor__ to satisfy numbers.Real abstract base class.
Edit: Suggestions have been to extend float and that was also my first idea but I lose my "stickiness" requirement. For example:
>>> class MyFloat(float):
def other_method(self):
print("other method output")
>>> mf = MyFloat(8)
>>> mf.other_method()
other method output
>>> o = mf + 9
>>> type(o)
<class 'float'>
>>> o.other_method()
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'float' object has no attribute 'other_method'