我有一个看起来像的代码。我的问题是我的代码改变了原始分数。
class Fraction:
""" This class represents one single fraction that consists of
numerator and denominator """
def __init__(self, numerator, denominator):
"""
Constructor. Checks that the numerator and denominator are of
correct type and initializes them.
:param numerator: fraction's numerator
:param denominator: fraction's denominator
"""
if not isinstance(numerator, int) or not isinstance(denominator, int):
raise TypeError
elif denominator == 0:
raise ValueError
self.__numerator = numerator
self.__denominator = denominator
def return_string(self):
""" Returns a string-presentation of the fraction in the format
numerator/denominator """
if self.__numerator * self.__denominator < 0:
sign = "-"
else:
sign = ""
return "{:s}{:d}/{:d}".format(sign, abs(self.__numerator),
abs(self.__denominator))
def complement(self):
""" Complement the fraction """
self.__numerator=-1*self.__numerator
return self
def reciprocal(self):
""" Reciprocal the fraction """
new_numerator=self.__denominator
new_denominator=self.__numerator
self.__numerator=new_numerator
self.__denominator=new_denominator
return self
所以我的代码给出了
>>> frac = Fraction(-2, 4)
>>> frac.return_string()
'-2/4'
>>> complement = frac.complement()
>>> complement.return_string()
'2/4'
>>> reciprocal = frac.reciprocal()
>>> reciprocal.return_string()
'4/2'
但它应该给我
>>> frac = Fraction(-2, 4)
>>> frac.return_string()
'-2/4'
>>> complement = frac.complement()
>>> complement.return_string()
'2/4'
>>> reciprocal = frac.reciprocal()
>>> reciprocal.return_string()
'-4/2'
所以基本上我的问题是,当我返回分数的补数或倒数时,它会替换原始分数,但我希望原始分数保持不变。
答案 0 :(得分:0)
在complement
和reciprocal
方法中,不要改变自身,而是创建Fraction
的新实例并将其返回。
def complement(self):
""" Complement the fraction """
return Fraction(-1*self.__numerator, self. __denominator)
def reciprocal(self):
""" Reciprocal the fraction """
new_numerator=self.__denominator
new_denominator=self.__numerator
return Fraction(new_numerator, new_denominator)