我发现自己在哪里,我在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__```
我希望这是有道理的...
我不知道另一个魔术函数,但是使arg1和arg2成为您所在类的永久变量可能同样有效。然后为您从其他每个魔术函数中调用的类创建一个方法。
编辑:
实际上,为什么不只使用getattr?因此每个魔术函数都将如下所示:
def __add__(self, rhs):
return getattr(self, 'decimal', self) + getattr(other, 'decimal', other)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句