2011-09-19 34 views
1

所以我正在學習如何使用類和python,我正在創建一個簡單的程序來執行有理數的算術運算。我正在創建一個名爲ArithmeticOperations的類。在這個類中,我有一個主函數定義,它提示用戶輸入2個有理數的分子和分母,然後根據用戶的選擇執行總和,差異,乘積或商。這些操作在一個單獨的功能中執行。現在,我已經創建的主要功能和產品功能,但是當我運行它,我得到的是說學習課程,但有一個奇怪的問題,我相信很簡單

TypeError: product() takes exactly 5 arguments (6 given)

一個錯誤,我相信這是一件簡單的,但我是新來的班,所以我有一點麻煩調試。這是我目前的程序:

class ArithmeticOperations: 

    # Given numbers u0, v0, and side, design a pattern: 
    def product(self,n1, d1, n2,d2): 
     self.numerator = n1*n2; 
     self.denominator = d1*d2; 
     print n1,'/',d1,'*',n2,'/',d2,'=',self.numerator,'/',self.denominator; 


    def main(self): 
     n1 = input('Enter the numerator of Fraction 1: '); 
     d1 = input('Enter the denominator of Fraction 1: '); 
     n2 = input('Enter the numerator of Fraction 2: '); 
     d2 = input('Enter the denominator of Fraction 2: '); 
     print '1: Add \n 2: Subtract\n 3: Multiply\n 4: Divide' ; 
     question = input('Choose an operation: '); 

     if question == 1: 
      operation = self.sum(self,n1,d1,n2,d2); 
     elif question == 2: 
      operation = self.difference(self,n1,d1,n2,d2); 
     elif question == 3: 
      operation = self.product(self,n1,d1,n2,d2); 
     elif question == 4: 
      operation = self.quotient(self,n1,d1,n2,d2); 
     else: 
      print 'Invalid choice' 


ao = ArithmeticOperations(); 
ao.main(); 
+1

[Python不是Java](http://dirtsimple.org/2004/12/python-is-not-java.html) –

+0

Augh,不要在Python中使用分號! – pawroman

回答

9

在方法調用中,沒有必要明確指定self。只需撥打:self.product(n1,d1,n2,d2);,瞭解所需的行爲。

類方法將始終有這個額外的self第一個參數,以便您可以引用方法體內的self。還要注意,不像this在java等語言中,self對於第一個參數的名稱來說只是一個常見的良好做法,但是您可以調用它,但是您可以調用它並使用它。

+0

相應地,可以通過調用'ArithemeticOperations.product(self,...)'來覆蓋/禁用多態。 –

+0

哦,我明白了。這很好,謝謝你! –

+0

@GuillermoAlvarez:沒問題:)如果有效,請考慮upvoting並接受答案。謝謝 :) –

相關問題