Python 蟒蛇3“;“魔术功能”;堆栈跟踪
我发现自己处于这样一种情况:我正在用Python3重新定义我的类的许多所谓的“魔法”属性或函数(Python 蟒蛇3“;“魔术功能”;堆栈跟踪,python,ipython-magic,Python,Ipython Magic,我发现自己处于这样一种情况:我正在用Python3重新定义我的类的许多所谓的“魔法”属性或函数(\uuuuuuuuuuuu添加,\uuuuuuu子,等等) 对于所有这些,我实现了相同的两行代码: arg1 = self.decimal if isinstance(self, Roman) else self arg2 = other.decimal if isinstance(other, Roman) else other 这些行所做的细节并不重要,但是,代码中的冗余会分散注意力。有没有另一
\uuuuuuuuuuuu添加
,\uuuuuuu子
,等等)
对于所有这些,我实现了相同的两行代码:
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__```
def __add__(self, rhs):
return getattr(self, 'decimal', self) + getattr(other, 'decimal', other)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/home/module.py”,第105行,在“magicFunction”中
文件“/home/module.py”,第110行,在```uuu gt```中
我希望这是有意义的…我不知道还有另一个神奇的函数,但如果将arg1和arg2作为您所在类的永久变量,可能同样有效。然后为类创建一个方法,该类在其他所有魔法函数中调用 编辑: 实际上,为什么不直接使用getattr呢?所以每个神奇的函数都是这样的:
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__```
def __add__(self, rhs):
return getattr(self, 'decimal', self) + getattr(other, 'decimal', other)
另一种说法是,我想有没有魔法函数在每次调用魔法函数时都会被调用?IPython magics是一种完全不同的野兽,看看