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

标签 python

因此,我正在学习如何使用类和 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 只是第一个参数名称的常见良好做法,但您可以调用它随心所欲地使用它。

关于python - 学习类(class),但有一个奇怪的问题,我确信这很简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7477614/

相关文章:

Python ctypes c_float.value 不返回值

python - 在 Python 中将浮点列表转换为字符串

python - 如何在具有共享模型和数据库的同一项目中拆分 Django 应用程序的部署?

python - python类的简单实例化

python - 我的 Django 网站在编辑时不显示任何表单

python - 在 tkinter 中使用 sys.stdout.write ("\r...")

python - 裁剪多边形并将其转换为灰度

python - 如果元组有一个共同元素,则合并元组

python - 无法安装 Python 包 [SSL : TLSV1_ALERT_PROTOCOL_VERSION]

python - 序列化用户模型