【问题标题】:Python Overloading OperationsPython 重载操作
【发布时间】:2016-10-09 18:04:41
【问题描述】:

我在 python 中创建了一个Rational 类,并为该类创建了__add____mull__ 等运算符。这是__init____add__ 函数的代码:

class Rational(object):
        def __init__(self, p, q=None):  # p/q
            if q is None: q = 1
            if q == 0: raise ZeroDivisionError("division by zero!")
            self.p = p
            self.q = q
            self.simplify()  # simplify the fraction

        def __iadd__(self, other):  # +=
            self.p = self.p * other.q + self.q * other.p
            self.q = self.q * other.q
            self.simplify()
            return self

        def __add__(self, other):
            r = Rational(self.p, self.q)
            r += other
            return r

现在我希望 python 能够理解 1 + Rational(1, 3)(一加三分之一)之类的东西。我怎么能实现这个?我是否必须添加 __radd__ 函数并在 other 为 int 时添加案例?还是有更简单的方法?

【问题讨论】:

    标签: python-2.7 operator-overloading


    【解决方案1】:

    我相信这可能是您正在寻找的:

    class Rational(object):
            def __init__(self, p, q=None):  # p/q
                if q is None: q = 1
                if q == 0: raise ZeroDivisionError("division by zero!")
                self.p = p
                self.q = q
                self.simplify()  # simplify the fraction
    
            def __iadd__(self, other):  # +=
                self.p = self.p * other.q + self.q * other.p
                self.q = self.q * other.q
                self.simplify()
                return self
    
            def __add__(self, other):
                if type(other) == int :
                    r = Rational(self.p + other * self.q , self.q)
                else:
                    r = Rational(self.p, self.q)
                    r += other
                return r 
    

    这样,您可以定义当您将 Rational 添加到另一种类型时会发生什么,在这种情况下,您要添加一个 int,因此它依赖于以下标识:

    (p/q)+r=(p+qr)/q

    我希望这会有所帮助!

    编辑:犯了一个愚蠢的数学错误,现已修复

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多