2012-10-12 62 views
0

我是新來的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) 
+0

我可能會混淆,但聽起來好像你只是想在結束調用self.reduce()您的\ _ \ _ INIT \ _ \_ 方法? – monkut

+1

'從分數進口Fraction' – jfs

回答

0

你有兩個問題:

  1. 你需要調用self.reduce()在構造函數__init__有在實例化階段調用的方法reduce()
  2. ,你也需要改變:

    def reduce(self): 
        gcd = findgcd(self.numerator, self.denominator) 
    

    到:

    def reduce(self): 
        gcd = self.findgcd(self.numerator, self.denominator) 
    

,否則您的實例將無法找到findgcd


下面的代碼將解決您的問題:

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 
     self.reduce() 

    def reduce(self): 
     gcd = self.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) 

>>>> f = Fraction(3,6) 
>>>> f 
1/2 
+0

感謝您的全面答覆,並+1表格指出'self.gcd'的另一個錯誤。順便說一句,我們有相同的姓氏。你是中國凱嗎? – mko

+0

@yozloy很高興幫助! (是的:)中國 - 加拿大準確) –

+0

太棒了!和WOW!'電線上的男人'也是我的最愛!我跟着你在twitter上 – mko

2

什麼阻止你調用self.reduce()__init__方法結束?

+0

+1爲簡單的答案,它的工作原理,我知道我當時在想什麼,謝謝 – mko

相關問題