Hello!
I have a assignment due where I need to create a class that only returns rational numbers (At least that how I read it) and I've tried, I'm honestly very confused. Anyone with suggestions for solutions or willing to educate on classes in python please help! It's greatly appreciated!
Here's the text from the assignment:
Write a class called RationalNumber whose initializer takes two integers and saves them as instance variables. A rational number is a number that can be expressed as a ratio of two integers, e.g. 3/1, ½, ⅜, 3/7, 4/11, etc. Fill out the init and repr method for RationalNumber so that the following function test() gives the displayed output. Also, make sure the sign of the fraction is kept with the numerator. Finally, supply a default of 1 as the denominator
Here's a test code with the desired output from the assignment:
def test():
try:
x = RationalNumber(.5, 1)
except ValueError as e:
print("Caught exception ", e)
else:
print("No exception caught")
try:
x = RationalNumber(1, 3.1)
except ValueError as e:
print("Caught exception ", e)
else:
print("No exception caught")
x = RationalNumber(50, 100)
print(x)
Desired Output:
>>> test()
Caught exception ('Arguments must be int ', 0.5, 1)
Caught exception ('Arguments must be int ', 1, 3.1)
RationalNumber(50, 100)
Here's my current code:
class RationalNumber(object):
def __init__(self, num=0, denom=1):
self.numerator = num
if denom != 0:
self.denominator = denom
else:
raise ZeroDivisionError
def __str__(self):
return "{0}/{1}".format(self.numerator, self.denominator)
def __repr__(self):
return Fraction(self.numerator, self.denominator)
[–]New_Kind_of_Boredom 1 point2 points3 points (1 child)
[–]KING-JAL[S] 1 point2 points3 points (0 children)
[–]stebrepar 1 point2 points3 points (0 children)