【问题标题】:Methods regarding Class Rational python关于 Class Rational python 的方法
【发布时间】:2013-12-04 19:31:56
【问题描述】:

我写了这两种方法,我仍然看不出这两种方法之间有什么区别..到目前为止,我的类工作正常,但由于方法是相同的,我仍然不明白为什么当我这样做时:x+1它调用 add ,而 1+x 它调用 radd ?

  def __add__(self,other):
    assert isinstance(other,(Rational,int,str))
    other=Rational(other)
    n = self.n * other.d + self.d * other.n
    d = self.d * other.d
    return Rational(n, d)

def __radd__(self,other):
    assert isinstance(other,(Rational,int,str))
    other=Rational(other)
    n =self.d * other.n + other.d * self.n
    d=other.d * self.d
    return Rational(n, d)

【问题讨论】:

    标签: class oop python-3.x rational-number


    【解决方案1】:

    给定表达式a + b,如果对象a实现__add__,它将被b调用:

    a.__add__(b)
    

    但是,如果 a 没有实现 __add__b 实现 __radd__(读作“右加”),那么 b.__radd__ 将被调用 a

    b.__radd__(a)
    

    解释这一点的文档是here

    【讨论】:

      【解决方案2】:

      当 Python 计算 X+Y 时,它首先调用

      X.__add__(Y)
      

      if that returns NotImplemented,然后是 Python 调用

      Y.__radd__(X)
      

      此示例演示了何时调用 __radd____add__

      class Commuter:
          def __init__(self,val):
              self.val=val
          def __add__(self,other):
              print 'Commuter add', self.val, other
          def __radd__(self,other):
              print 'Commuter radd', self.val, other
      
      x = Commuter(88)
      y = Commuter(99)
      x+1
      # Commuter add 88 1
      
      1+y
      # Commuter radd 99 1
      
      x+y
      # Commuter add 88 <__main__.Commuter instance at 0xb7d2cfac>
      

      在这种情况下:

      In [3]: (1).__add__(y)
      Out[3]: NotImplemented
      

      所以y.__radd__(1) 被调用。

      【讨论】:

      • 当我在没有 __radd__ 的情况下运行我的课程时它不会给我,但是当我运行它时,它允许我正常运行它,所以我想这意味着这没关系? def __add__(self,other): 断言 isinstance(other,(Rational,int,str)) other=Rational(other) n = self.n * other.d + self.d * other.n d = self.d * other .d return Rational(n, d) def __radd__(self,other): assert isinstance(other,(Rational,int,str)) other=Rational(other) n =self.d * other.n + other.d * self.n d=other.d * self.d return Rational(n, d)
      • 我不确定你的问题是什么,而且在 cmets 中阅读代码真的很难。请编辑您的原始问题,在此处添加代码,使用 {} 按钮,以便正确格式化代码。
      • 您正在为 Rational 类定义 __add____radd__xRational 的一个实例,但 1 不是。 1intint 类有自己的 __add____radd__ 方法。 1+x 导致 (1).__add__(x) 被调用。这将返回 NotImplemented,从而导致调用 x.__radd__(1)。 (顺便说一句,由于您的__add____radd__ 方法是相同的,您可以只说__radd__ = __add__ 而不是用def __radd__(self, other): 定义__radd__ ....)
      • 我有一个小问题,假设我正在使用 add ,我将一个有理数添加到一个它不起作用的有理数上,如果它是 int ,那么一切都是好吧..至于 sub 反过来,当它的 Rational - Rational 时它工作得很好,但是当它的 Rational - int 时,它不起作用..可能是什么问题?跨度>
      猜你喜欢
      • 1970-01-01
      • 2011-12-19
      • 2017-06-13
      • 2010-12-03
      • 2014-11-12
      • 2011-11-20
      • 1970-01-01
      • 2019-05-03
      相关资源
      最近更新 更多