I’m new to Python,
After initialising an instance f of class Fraction, I want the method reduce has been invoked, so the print result is after reduced
f = Fraction(3,6)
print f #=> 1/2 not 3/6
here’s the code:
class Fraction(object):
'''Define a fraction type'''
def __init__(self, num=0, denom=1):
'''Create a new Fraction with numerator num and denominator demon'''
self.numerator = num
if denom != 0:
self.denominator = denom
else:
raise ZeroDivisionError
def reduce(self):
gcd = findgcd(self.numerator, self.denominator)
self.numerator /= gcd
self.denominator /= gcd
def findgcd(self, x, y):
gcd = None
min_number = min(x, y)
for i in range(min_number, 1, -1):
if x % i == 0 and y % i == 0:
gcd = i
return gcd
def __repr__(self):
return "{0}/{1}".format(self.numerator, self.denominator)
You have two problems:
self.reduce()in your constructor__init__to have methodreduce()invoked during the instantiation phase.you also need to change:
to:
because otherwise your instance will not be able to find
findgcd.The following code will fix your problem: