首先,我必須說我對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)
除了回答這個問題的,如果你對我的代碼中的任何意見,我很樂意傾聽您的反饋和學習:)