I find myself in a situation where I am redefining a lot of the so called "magic" attributes or functions of my class in Python3 (__add__
, __sub__
, etc.)
For all of these, I implement the same two lines of code:
arg1 = self.decimal if isinstance(self, Roman) else self
arg2 = other.decimal if isinstance(other, Roman) else other
The details of what these lines do isn't important, however, the redundancy in my code is distracting. Is there another "magic" function that is a middle ground between this and it being called in the REPL?
For example:
>> Class(9) + Class(3)
... (somewhere in python module)
... def __magicFunction__(self, rhs):
... arg1 = self.decimal if isinstance(self, Roman) else self
... arg2 = other.decimal if isinstance(other, Roman) else other
...
... THEN
...
... def __add__(self, rhs):
... return arg1 + arg2
...
12
with a stacktrace of something like this:
Traceback (most recent call last):
File "< stdin>", line 1, in < module>
File "/home/module.py", line 105, in ```__magicFunction__```
File "/home/module.py", line 110, in ```__gt__```
I hope this makes sense...