使用radd方法在类之间添加

use*_*139 4 python-3.x

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
Run Code Online (Sandbox Code Playgroud)

我的问题是:我有两个不同的类,我想在一个类中定义它们的添加,并为该类定义add和radd(在这个例子中是exampleclass2.我不想创建一个add方法适用于exampleclass1以添加exampleclass2.

就像现在一样,它只是忽略了它.我也试图提出错误,但这也没有用.非常高兴能得到我的帮助!:)

Len*_*bro 16

__radd__仅在左对象没有__add__方法时调用,或者该方法不知道如何添加两个对象(通过返回NotImplemented来标记).这两个类都有一个__add__方法,它不返回NotImplemented.因此__radd__永远不会调用该方法.


小智 11

假设您正在实现一个类,您希望通过运算符重载使其表现得像数字一样。所以你在你的类中实现了add,现在像这样的表达式myobj + 4可以按照你想要的方式工作并产生一些结果。这是因为myobj + 4被解释为myobj.__add__(4),并且您的自定义方法可以执行任何操作,将 4 添加到您的自定义类中。

\n

4 + myobj但是,像which is true 这样的表达式又如何呢(4).__add__(myobj)?4 是 Python 内置类型的实例,它的add方法对新类型一无所知,因此它将返回一个特殊值 NotImplemented。(解释器识别出来自add的这个特殊值,并引发 TypeError 异常,该异常会终止您的程序,这是您实际看到的行为,而不是返回的特殊值。)

\n

myobj + 4如果有效但4 + myobj无效,那么运算符重载会很糟糕。这是任意的和限制性的\xe2\x80\x8a\xe2\x80\x94\xe2\x80\x8a加法应该是可交换的。进入__radd__。Python 将首先 try (4).__add__(myobj),如果返回 NotImplemented Python 将检查右侧操作数是否实现了radd,如果实现了,它将调用myobj.__radd__(4)而不是引发 TypeError 。现在一切都可以照常进行,因为您的类可以处理这种情况并实现您的行为,而不是内置类型的添加是固定的并且不知道您的类。

\n

例子:

\n
class X:\n    \n    def __init__(self, num):\n        self.num = num\n\n    def __str__(self):\n        return str(self.num)\n\n    def __add__(self, other):\n        return self.num + other.num\n    \n    __radd__ = __add__\n\n\nclass Y:\n\n    def __init__(self, num):\n        self.num = num\n\n    def __str__(self):\n        return str(self.num)\n\n\nx = X(5)\ny = Y(10)\n\nprint(x+y)\n\nprint(y+x)\n
Run Code Online (Sandbox Code Playgroud)\n


Adi*_*asi 7

__radd__仅当左操作数不支持相应操作且操作数为不同类型时,才会调用这些函数。例如,

class X:
  def __init__(self, num):
    self.num = num
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
>>> 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'
Run Code Online (Sandbox Code Playgroud)