Python:运算符重载特定类型

Hoo*_*ked 5 python operator-overloading

我希望能够让我的类的运算符以我定义的方式与常规类型进行交互.让我们说,例如,我有:

class Mynum(object):
  def __init__(self, x):
   self.x = x
  def __add__(self, other):
   return self.x + other.x

a = Mynum(1)
b = Mynum(2)

print a+b
Run Code Online (Sandbox Code Playgroud)

这很好用,但现在如果我尝试这样做:

print a+2
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,因为int没有一个名为的成员x.我如何在课堂上定义Mynum+ int?这听起来像是装饰者或元类的工作,但我对他们的用法非常不熟悉.这个问题似乎相似,但并不完全相同.

Sil*_*ost 14

def __add__(self, other):
    if isinstance(other, self.__class__):
        return self.x + other.x
    elif isinstance(other, int):
        return self.x + other
    else:
        raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))
Run Code Online (Sandbox Code Playgroud)

  • 你不应该返回 `NotImplemented` 而不是自己提出和异常吗? (2认同)

unu*_*tbu 5

class Mynum(object):
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        try:
            return self.x + other.x
        except AttributeError:
            return self.x + other
    __radd__=__add__

a = Mynum(1)
b = Mynum(2)

print(a+b)
# 3
print(a+2)
# 3
print(2+a)
# 3
Run Code Online (Sandbox Code Playgroud)