__add __,__ sub __,__ mul__和__div__的示例?

时间:2014-02-21 14:31:53

标签: python python-3.x

我不知道如何使用这些方法。你能提供一些简单的例子吗?

1 个答案:

答案 0 :(得分:5)

在这里,让我做一个NonNegative:

 class NonNegative(object):
   def __init__(self, x):
     if x < 0: raise Exception()
     self.x = x

   @property
   def value(self):
     return self.x

   @value.setter
   def set_value(self, that):
     if that < 0: raise Exception()
     self.x = that

   def __add__(self, x):
     if isinstance(x, NonNegative):
       return NonNegative(x.value + self.x)
     else:
       return NotImplemented

像这样使用:

   a = NonNegative(1)
   b = NonNegative(2)
   c = a + b

所以调用+会委托给__add__