给定某个类,你可以实现基本的二进制操作(__add__
、__sub__
等(并能够执行obj1 + obj2
或obj1 + 3
,但由于显而易见的原因,3 + obj1
会失败,因为内置的python类型不太可能处理你的类。
从来没有想过太多,只是认为事情就是这样,直到我意识到有成功完成3 + obj1
的例子。例如:
import numpy as np
obj1 = np.array([1,2,3])
3 + obj1
Out[19]: array([4, 5, 6])
如何允许我的类在左侧的 python 内置类型和右侧的对象之间的操作中成功使用?
class DataStruct:
def __init__(self,x,y):
self._x = x
self._y = y
def __add__(self,other):
if isinstance(other,DataStruct):
x = self._x + other._x
y = self._y + other._y
else:
x = self._x + other
y = self._y + other
return DataStruct(x,y)
def __repr__(self):
return f'{self._x},{self._y}'
obj1 = DataStruct(1,2)
obj2 = DataStruct(2,4)
obj1 + obj2
Out[33]: 3,6
obj1 + 3
Out[34]: 4,5
3 + obj1
Traceback (most recent call last):
File "<ipython-input-35-056b6e7e1462>", line 1, in <module>
3 + obj1
TypeError: unsupported operand type(s) for +: 'int' and 'DataStruct'
您正在寻找的魔术函数是 __radd__
,当您的类位于加法的右侧时,它会处理加法。一般来说,有一整套这些__r<OPERATOR>__
函数来处理这些情况,如果你想支持你的类处于两个位置,除了__add__
之外,你还需要实现这些函数(不假设操作总是可交换的(。