0

我发现自己处于一种情况,我在 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__```  

我希望这是有道理的...

4

1 回答 1

1

我不知道另一个魔术函数,但是将 arg1 和 arg2 设为您所在的类的永久变量可能同样有效。然后为您从其他所有魔术函数中调用的类创建一个方法。

编辑:

实际上,你为什么不直接使用 getattr 呢?所以每个魔术函数看起来像这样:

def __add__(self, rhs):
  return getattr(self, 'decimal', self) + getattr(other, 'decimal', other)
于 2014-10-13T06:52:23.393 回答