算数运算符重载:__add__ 、 __radd__ 、 __iadd__为例

版权声明:转载请标明 https://blog.csdn.net/weixin_42068613/article/details/81394100

__add__表示‘左加’,若对象在+右边则会报错TypeError

class Number:
      def __init__(self, num):
          self.num = num

      def __str__(self):
          return str(self.num)

      # 对象出现在'+'的左边时自动触发
      def __add__(self, other):
          print('__add__')
          return self.num + other

__radd__表示‘右加’,若对象在+左边会报错

class Number:
      def __init__(self, num):
          self.num = num

      def __str__(self):
          return str(self.num)

      # 对象出现在'+'的左边时自动触发
      def __radd__(self, other):
          print('__radd__')
          return self.num + other

__iadd__表示‘+=’

class Number:
      def __init__(self, num):
          self.num = num

      def __str__(self):
          return str(self.num)

      # 对象出现在'+'的左边时自动触发
      def __add__(self, other):
          print('__iadd__')
          return self.num + other

猜你喜欢

转载自blog.csdn.net/weixin_42068613/article/details/81394100