On 30/09/2021 18.11, Anil Anvesh wrote: > I want to write a python calculator program that has different methods to > add, subtract, multiply which takes 2 parameters. I need to have an execute > method when passed with 3 parameters, should call respective method and > perform the operation. How can I achieve that? > > > > class calc(): > def __init__(self,a,b): > self.a=a > self.b=b > > def ex(self,fun): > self.fun=fun > if fun=="add": > self.add() > > def add(self): > return self.a+self.b > def sub(self): > return self.a-self.b > def mul(self): > return self.a*self.b > def div (self): > return self.a/self.b > def execu( > obj1=calc() > obj1.execu("add",1,,2) >
This is a common course-assignment. NB the code-examples below are incomplete. You may need to research these techniques further, and thus learn how 'it' all fits-together (I set 'homework' rather than doing it!) There are several techniques which can be employed and/or combined here. 1 if-elif 'ladder' 2 dict[ionary] as select/case construct 3 functions as 'first-class objects' The basic problem is to take a 'command' which is formatted as a str[ing], and decide which of several options to choose: 1 if-elif is a simple and easy-to-read solution: if command == "add": do_this... elif command == "sub": do_that... ... else: # oops: "I'm afraid I can't do that, Dave" # don't forget to add a 'catch-all' to handle user-error! 2 using a dict is shorter and avoids some of the 'boiler-plate' repetition which causes many of us to rebel against using the above. We use the command received from the user as a key into the dict. 3 a function and/or its name is as much data as the 'variable' "command" or indeed the str-constant "add" - once it has been defined! Thus it is possible to treat functions like anything else: data_as_string = "my string" # can be likened to:- def my_function(): pass data_as_function = my_function Note that (like most else), the function must be defined before it can be 'used'! Returning to the stated-problem: def add( etc ): ... then using the if-elif 'ladder' above as a framework create a dict which 'links' the input command (as str) to the applicable function: calculator = { "add": add, "sub": sub, # indeed we can become rather more 'creative' "+" " add, ... } Thereafter, we can apply the dict to solve the problem: calculator.get( command, "Error message/advice, eg mentioning add, or + etc" ) NB it has been left to you to perfect the technique so that the value(s) to be calculated are properly communicated to the chosen function. PS you may find the Python-Tutor Discussion List helpful -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list