【问题标题】:Python. Defining a new operation between two built-in typesPython。在两个内置类型之间定义一个新操作
【发布时间】:2017-05-16 14:05:45
【问题描述】:

首先我不得不说我对 Python 和一般编程很陌生,所以这个问题之前可能已经被问过,但我只是不知道我应该用什么具体的词来寻找这个问题。

我正在尝试创建一个供个人使用的模块,该模块以更象征性的方式处理有理数。我知道有模块可以做到这一点,但我的目标不是使用模块,而是通过制作来学习。我的问题是,当我编写特定操作(即 2 f 3)时,是否有某种方法可以让 Python 实例化一个新的 Rational 对象,而不是每次我想创建一个新的 Rational 时都必须编写 Rational(2,3)。这是到目前为止的代码:

class Rational:
    """Contains a rational number and the 
    information to simplify it and operate."""

    def __init__(self, a, b):
        if type(a) == int and type(b) == int:
            self.num = a
            self.den = b
            self.simplify()
        else:
            raise TypeError("Both arguments must be int.")

    def __repr__(self):
        """Returns the explicit syntax to create
        an object with the same attributes."""

        return "Rational({}, {})".format(self.num, self.den)

    def __str__(self):
        """Returns the fraction as a/b unless the denominator 
        is 1, in which case it returns only the numerator."""
        if self.den != 1:
            return str(self.num) + "/" + str(self.den)
        else:
            return str(self.num)

    def __add__(self, other):
        """Rationals can be added to other rationals, int and float."""

        if type(other) == float:
            return self.to_float() + other
        elif type(other) == int:
            s = Rational(self.num + other * self.den, self.den)
            return s
        elif type(other) == Rational:
            s = Rational(
                self.num * other.den + other.num * self.den, 
                self.den * other.den)
            s.simplify()
            return s
        else:
            return NotImplemented

    def simplify(self):
        """Simplifies the fraction and takes the sign to the numerator."""

        # If the num is 0 we don't care about the den.
        if self.num == 0:
            self.den = 1
        else:
            # Divide num and den by their gcd.
            d = gcd(self.num, self.den)
            self.num //= d
            self.den //= d

            # If the den is negative, move the sign to the num.
            if self.den > 0:
                pass
            else:
                self.num = -self.num
                self.den = -self.den

    def to_float(self):
        return float(self.num / self.den)

def gcd(a, b):
    """Returns the gcd of two integers."""

    while b:
        a, b = b, a % b
    return abs(a)

除了回答问题,如果您对我的代码有任何建议,我非常乐意听取您的反馈并学习 :)

【问题讨论】:

    标签: python class operator-keyword


    【解决方案1】:

    哇,你正在寻找的东西是不可能的,不仅在 python 中,而且在几乎所有编程语言中。

    因为你想要的是定义一个新的操作符,这也意味着你需要一个新的关键词来实现这一点。但是关键字列表必须固定,因为编译器/解释器也不会被您的代码更新。

    【讨论】:

      【解决方案2】:

      不,您不能在 python 中定义新的运算符。但是,您可以覆盖现有运算符的行为。

      python 文档有更多详细信息:https://docs.python.org/2/reference/datamodel.html

      【讨论】:

        猜你喜欢
        • 2016-09-10
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-11
        • 1970-01-01
        相关资源
        最近更新 更多