简体   繁体   中英

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

Firstly, your drive_command line has incorrect syntax - you should have the arguments as this drive_command(self, command, x, y) , otherwise python will get confused. To call your add function, simply use the following:

self.add(x,y)

in place of

self.add()

Hope this helps!

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)

Use the getattr function:

class calculator:
    def __init__(self):
        pass
    def add(self, num1, num2):
        return num1+num2
    def drive_command(self, command,x,y):
        return getattr(self, command)(x, y)

c = calculator()
print(c.drive_command('add',10,10))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM