Skip to main content
 首页 » 编程设计

python之学习类(class),但有一个奇怪的问题,我确信这很简单

2025年05月04日14lautakyan007

因此,我正在学习如何使用类和 Python,并且正在创建一个简单的程序来执行有理数的算术运算。我正在创建一个名为 ArithmeticOperations 的类。在这个类中,我有一个主函数定义,提示用户输入 2 个有理数的分子和分母,然后根据用户的选择执行和、差、积或商。这些操作在单独的函数中执行。现在我已经创建了 main 函数和 product 函数,但是当我运行它时,我得到一个错误

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(); 

请您参考如下方法:

在方法调用中,无需显式指定self。只需调用:self.product(n1,d1,n2,d2);,以获得所需的行为。

类方法总是有这个额外的 self 第一个参数,这样你就可以在方法体内引用 self。另请注意,与 java(以及更多)等语言中的 this 不同,self 只是第一个参数名称的常见良好做法,但您可以调用它随心所欲地使用它。