2017-05-16 24 views
0

首先,我必須說我對Python和編程一般都很陌生,所以這個問題以前可能已經被問過了,但我只是不知道具體的詞是什麼應該用來尋找這個。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) 

除了回答這個問題的,如果你對我的代碼中的任何意見,我很樂意傾聽您的反饋和學習:)

回答

0

哇,你在找什麼的是不可能的,不只是在python,但幾乎在每一個編程語言。

因爲你想要的是定義一個新的操作符,這也意味着你需要一個新的關鍵詞來實現這一點。但是關鍵詞列表必須是固定的,因爲編譯器/解釋器不會被代碼更新。

相關問題