Search code examples
pythonpython-3.xfunctionmethod-call

calling method from another method which takes 3 parameters in the same class


I was writing a code for calculator by creating class name "calculator" which takes methods for add, subtract, multiply and divide. These methods takes two parameters and perform respective action.

Now, I have to create another method name "drive_command" which takes 3 parameters. First parameter takes the string that can be either 'add', 'subtract', 'multiply', 'divide' and the other two parameter take the numbers and it will call the specific method based on the string that we will pass in the drive_command method.

So how I supposed to call method from another method which takes parameter in the same class?

class calculator:
    def __init__(self):
        pass
    def add(self, num1, num2):
        self.num1 = num1
        self.num2 = num2
        return num1+num2
    def drive_command(command,x,y):
        if command == "add":
            self.add()

Solution

  • Just add self parameter in drive_command function.And call self.add(x,y).

    class calculator:
        def __init__(self):
            pass
        def add(self, num1, num2):
            self.num1 = num1
            self.num2 = num2
            return num1+num2
        def drive_command(self,command,x,y):
            if command == "add":
                return self.add(x,y)
    
    c = calculator()
    value = c.drive_command('add',10,10)
    print(value)