开发者

Learning classes but having an odd issue that I am sure is simple

开发者 https://www.devze.com 2023-04-05 19:28 出处:网络
So I am learning how to use classes and python and I am creating a simple program to perform arithmetic operations with rational numbers. I am creating a class called ArithmeticOperations. In this cla

So I am learning how to use classes and python and I am creating a simple program to perform arithmetic operations with rational numbers. I am creating a class called ArithmeticOperations. In this class I have a main function definition which prompts the user for the numerator and denominator of 2 rational numbers, then performs either the sum, difference, product, or quotient based on the choice of the user. The operations are performed in a separate function. Right now I have created the main function and the product function, but when I run it I get an error that says

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

I am sure this is something simple but I am new to classes so i am having a bit of trouble debugging. Here is my current program:

class ArithmeticOperations:

    # Given numbers u0, v0, and side, design a pattern:
    def product(self,n1, d1, n2,d2):
        self.numerator = n1*n2;
        self.denom开发者_StackOverflow中文版inator = 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();


In the method call, there is no need to explicitly specify self. Just call: self.product(n1,d1,n2,d2);, for the desired behavior.

Class methods will always have this extra self first argument, so that you can refer to the self inside the method body. Note also that unlike this in languages such as java (and many more), self is just a common good practice for the name of the first argument, but you could call it however you like and use it all the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消