代码之家  ›  专栏  ›  技术社区  ›  Hooked

Python:运算符重载特定类型

  •  5
  • Hooked  · 技术社区  · 16 年前

    我希望能够让我的类的操作符以我定义的方式与常规类型交互。比如说,我有:

    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
    

    print a+2
    

    我有一个错误,因为 int 没有名为的成员 x . 我该如何定义 Mynum 内景 This question 似乎相似,但不完全相同。

    3 回复  |  直到 9 年前
        1
  •  15
  •   SilentGhost    16 年前
    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))
    
        2
  •  4
  •   unutbu    16 年前
    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
    
        3
  •  2
  •   Hazok    13 年前

    为什么要使用额外的切换和/或异常处理?使用以下方法更简单:

    class MyNum(object):
        def __init__(self, x):
            self.x = x
        def __add__(self, other):
            return other + self.x
        __radd__ = __add__
    x = MyNum(5)
    y = MyNum(6)
    print x + 2
    7
    print 2 + x
    7
    print x + y
    11
    print y + x
    11