【发布时间】: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