使用radd方法之间的类之间的加法
问题描述:
class exampleclass1:
def __init__(self, data):
self.data = data
def __add__(self, other):
if isinstance(other, int):
print('blabla')
class exampleclass2:
def __init__(self, data):
self.data = data
def __add__(self, other):
if isinstance(other, exampleclass1):
print("it's working yay")
__radd__ = __add__
a = exampleclass1('q')
b = exampleclass2('w')
a+b
我的问题是这样的:我有两个不同的类,我想定义它们只在一个类中的添加,并为该类定义add和radd(在本例中这是exampleclass2。我不想创建一个add方法,可用于exampleclass1添加exampleclass2使用radd方法之间的类之间的加法
因为它是现在它只是忽略它,我也尝试提出错误,但也没有工作。高兴得到我的帮助!:)
答
__radd__
仅在左对象没有__add__
方法od,或者该方法不知道如何添加两个对象(它通过返回NotImplemented来标记)。两个类都有一个__add__
方法,它不返回NotImplemented。因此__radd__
方法永远不会被调用。
答
这些功能
__radd__
如果左操作数不 不支持相应的操作只被调用和操作数是 不同的类型。例如,
class X:
def __init__(self, num):
self.num = num
class Y:
def __init__(self, num):
self.num = num
def __radd__(self, other_obj):
return Y(self.num+other_obj.num)
def __str__(self):
return str(self.num)
>>> x = X(2)
>>> y = Y(3)
>>> print(x+y)
5
>>>
>>> print(y+x)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-60-9d7469decd6e> in <module>()
----> 1 print(y+x)
TypeError: unsupported operand type(s) for +: 'Y' and 'X'
啊,NotImplemented,这正是我一直在寻找的功能。尼斯 – user1187139 2012-02-04 02:36:31