为不同的状态重载运算符

时间:2016-03-14 17:54:26

标签: python operator-overloading

如何在Python中为不同的状态重载运算符?例如,查看以下C ++代码:

class Rational
{    
    int num,denum;
    Rational();
    Rational(int a);
    Rational(int a,int b);

    Rational operator+(Rational r){
    Rational h;
    h.num = (num*r.denum + denum*r.num);
    h.denum = (denum*r.denum);
    h.reduce();
    return h;
    }

    Rational operator+(int x){
    Rational h;
    h.num = num + x*denum;
    h.denum = denum;
    h.reduce();
    return h;
    }
};

我想为两个状态重载+运算符:首先将Rational数加到整数;第二个是将Rational数字添加到另一个Rational数字。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

Python将操作符处理委托给操作符中涉及的对象。请参阅Python datamodel文档中的Emulating numeric types section

对于+运营商,如果您希望支持将自定义类型添加到现有类型(例如5 + Rational(),请提供__add__ method和/或实施__radd__ method })。请注意您如何处理不支持的操作'案件;你返回单个NotImplemented对象,不要引发异常。

答案 1 :(得分:0)

您只能为__add__课程提供Rational的一个定义;该函数必须查看其他参数的类型才能做正确的事情。例如:

class Rational(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __add__(self, other):
        if isinstance(other, Rational):
            d = self.b * other.b
            return Rational(self.a * other.b + other.b * self.a, d)
        elif isinstance(other, int):
            return Rational(self.a + self.b * other, self.b)
        else:
            return NotImplemented

    # __add__ is invoked for Rational + other
    # __radd__ will be called by other + Rational if other doesn't
    # know about your class.
    def __radd__(self, other):
        return self.__add__(other)