学习课程,但有一个奇怪的问题,我相信很简单

Gui*_*rez 1 python

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

TypeError:product()只需要5个参数(给定6个参数)

我确信这很简单,但我是新手,所以我在调试时遇到了一些麻烦.这是我目前的计划:

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();
Run Code Online (Sandbox Code Playgroud)

Era*_*man 9

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

类方法总是会有这个额外的self第一个参数,因此您可以引用方法体内的self.另请注意,与thisjava(以及更多)等语言不同,self它只是第一个参数名称的常见良好实践,但您可以调用它,但是您可以使用它来完全相同.