我需要为一个对象创建一个运算符,我想知道什么是最好的方法。
例如对于运算符添加
我可以这样写吗?
def _add_(self,other):
new=self.add(self,other)// can I write like that?
return new
感谢您的帮助!
请您参考如下方法:
您将使用 python 魔术函数 __add__ 来处理 +:
例子:
class A():
def __init__(self, num):
self.num = num
def __add__(self, other):
return self.num + other
a = A(6)
>>> print a+5
11
为了更大的灵 active ,您还应该定义 __radd__,这是用于反向加法的情况 5+a,它不在上面的例子。
class A():
def __init__(self, num):
self.num = num
def __add__(self, other):
return self.num + other
def __radd__(self, other):
return self.num + other
>>> a = A(6)
>>> print 5+a
11
>>> print a+5
11
或者如果你想返回一个对象而不是一个int,你可以这样做:
class A():
def __init__(self, num):
self.num = num
def __add__(self, other):
return A(self.num + other)
a = A(5)
b = a+5
print b.num
10
print a.num
5
上面已经证明的是operator overloading .它通过让用户为运算符定义自定义方法来覆盖用于处理运算符的内置默认方法。
这是一个您可能会发现对 which operators can be overloaded 有用的列表
