Reputation: 8945
How to perform arithmetic on classes with a basic type as a subclass, where the result is of the same class?
For example, running:
class Speed(float):
def __add__(self, speed):
if isinstance(speed, Speed):
return Speed(self + speed)
else:
raise NotImplementedError()
def __repr__(self):
return f'Speed({self} mph)'
Speed(2) + Speed(2)
Results in the below instead of the expected Speed(4)
:
RecursionError Traceback (most recent call last)
<ipython-input-13-ce1336693f4a> in <module>
----> 1 Speed(2) + Speed(2)
<ipython-input-11-f161664be9bc> in __add__(self, speed)
3 def __add__(self, speed):
4 if isinstance(speed, Speed):
----> 5 return Speed(self + speed)
6 else:
7 raise NotImplementedError()
... last 1 frames repeated, from the frame below ...
<ipython-input-11-f161664be9bc> in __add__(self, speed)
3 def __add__(self, speed):
4 if isinstance(speed, Speed):
----> 5 return Speed(self + speed)
6 else:
7 raise NotImplementedError()
RecursionError: maximum recursion depth exceeded while calling a Python object
How to correctly perform arithmetic on such a class?
Upvotes: 0
Views: 40
Reputation: 4135
You need to convert both self
and speed
to float before handing it to the +
operator, because otherwise it will try to call the method again on one of the Speed
instances. This will happen recursively without bail condition and eventually err out as it did in your case.
return Speed(float(self) + float(speed))
Upvotes: 1