我是新來的Python,如何在實例的初始化過程中調用某些方法在Python
初始化Fraction
類的一個實例f
後,我想reduce
已調用的方法,所以print
結果降低
f = Fraction(3,6)
print f #=> 1/2 not 3/6
這裏後的代碼:
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)
我可能會混淆,但聽起來好像你只是想在結束調用self.reduce()您的\ _ \ _ INIT \ _ \_ 方法? – monkut
'從分數進口Fraction' – jfs