-2

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()
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ritesh kumar
  • 17
  • 1
  • 3

3 Answers3

1

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)
Vijay
  • 116
  • 1
  • 7
  • If I want to make "drive_command" case-insensitive that is even if the user passes 'adD' as command it should perform addition on two numbers then what i have to do? – Ritesh kumar Jul 05 '20 at 11:02
  • Just use command.lower()=='add' instead of command == 'add' in if statement inside drive_command function – Vijay Jul 05 '20 at 15:24
0

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!

  • Or, add `x` and `y` as class members in `drive_command`, then nothing has to be passed in to `add()`. – S3DEV Jul 05 '20 at 08:28
  • 1
    Yes, that could be a useful option. – sciencepiofficial Jul 05 '20 at 08:30
  • Please don't suggest to carry around function arguments as attributes. There shouldn't be a class in the first place, but misusing it as a function container is far less of a code smell than indirectly passing parameters. – MisterMiyagi Jul 05 '20 at 09:21
0

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))
rioV8
  • 24,506
  • 3
  • 32
  • 49