【发布时间】:2014-02-11 08:36:58
【问题描述】:
目前正在写一个作业来编写一个创建分数的类。类的前几行如下:
class Fraction():
#constructor
"""
Post-condition: User calls class with 0, 1, or 2 integers.
Post-condition: Fraction object is created. Numerator and denominator each default
to 1.
"""
def __init__(self, numerator = 1, denominator = 1):
self.__numerator = numerator
self.__denominator = denominator
#__str__ method
"""
Pre-condition: User has created a fraction object and has call the print function
to display the fraction value.
Post-condition: Method checks for a denominator of zero and returns an error message
if true. It will then check for float values in the numerator and denominator and
convert them to integers if true. It will then check if the numerator and denominator
are the same number and return a 1 if true. Next it checks if the denominator can be
divided into the numerator with a zero remainder and returns a whole number if true.
Last, it will return a fraction.
"""
def __str__(self):
#check for float in denominator
if isinstance(self.__denominator, float):
self.__denominator = int(self.__denominator)
#check for float in numerator
if isinstance(self.__numerator, float):
self.__numerator = int(self.__numerator)
#check for equality in numerator and denominator
if self.__numerator == self.__denominator:
return 1
#check for zero remainder division
elif self.__numerator % self.__denominator == 0:
wholeNumber = self.__numerator / self.__denominator
return str(wholeNumber)
else:
divisor = self.__numerator
tmpDenom = self.__denominator
while tmpDenom:
divisor, tmpDenom = tmpDenom, divisor % tmpDenom
self.__numerator = self.__numerator // divisor
self.__denominator = self.__denominator // divisor
return str(self.__numerator) + '/' + str(self.__denominator)
在终端和 IDLE 中运行测试时,我使用以下代码来测试我的输出:
from modFraction import Fraction
frac1 = Fraction(15, 16)
print(frac1)
frac2 = Fraction(17, 18)
print(frac2)
print(frac1 + frac2)
当我运行输出时,我最终得到以下输出:
15.0/16.0
17.0/18.0
271.0/144.0
我的整数输入在哪里转换为浮点数???
【问题讨论】:
-
为什么
__str__方法中有这么多类型检查和转换?这一切都应该发生在__init__,而不是在需要打印的时候。 -
当我运行
print(Fraction(15, 16))时,我得到15/16。仔细检查您正在运行的 Python 版本,也许? -
@Blackwell 有时,如果您有旧的
.pyc文件,就会发生巫术。删除相关目录下的所有.pyc文件,然后重试。 -
@juliohm:因为这是一个作业。
-
@jozzas:谢谢。我想我的运气不好是 IDLE ......不会发生在终端。
标签: python python-3.x