我发现自己处于一种情况,我在 Python3 中重新定义了我的类的许多所谓的“魔法”属性或函数(__add__
,__sub__
等)。
对于所有这些,我实现了相同的两行代码:
arg1 = self.decimal if isinstance(self, Roman) else self
arg2 = other.decimal if isinstance(other, Roman) else other
这些行所做的细节并不重要,但是,我的代码中的冗余会分散注意力。是否有另一个“神奇”函数是介于它和它在 REPL 中被调用的中间地带?
例如:
>> 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
有这样的堆栈跟踪:
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__```
我希望这是有道理的...