0

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...

Tim Zimmermann
  • 6,132
  • 3
  • 30
  • 36
Jeremy
  • 1,717
  • 5
  • 30
  • 49
  • Another way to phrase this I guess would be is there any magic function that is invoked every time a magic function is called? – Jeremy Oct 13 '14 at 06:44
  • IPython magics are a completely different beast, have a look at http://stackoverflow.com/questions/15196360/python-overloading-several-operators-at-once – filmor Oct 13 '14 at 06:49

1 Answers1

1

I don't know about another magic function, but it would probably be just as productive to make arg1 and arg2 permanent variables of the class you're in. Then make a method for the class that you call from within every other magic function.

EDIT:

actually, why don't you just use getattr? so each magic function would look something like this:

def __add__(self, rhs):
  return getattr(self, 'decimal', self) + getattr(other, 'decimal', other)
Jeremy
  • 322
  • 2
  • 10