How to pass a method as argument?

Anil Anvesh anilanvesh at
Fri Oct 1 01:59:57 EDT 2021

On Friday, October 1, 2021 at 6:04:34 AM UTC+5:30, Mats Wichmann wrote:
> On 9/29/21 23: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? 
> >
> let me add - this is probably not the place you are in your Python 
> learning, so don't worry about this, but the operator module is designed 
> for these kind of usages, when you want to pass an operator like + - 
> etc. but of course can't pass the op itself to take actions because it's 
> not a callable - the operator module has callables that can be used.

I solved it with simple if condition and without using init

#calculator class with arithmetic methods

class calc:
    def execute(self, func, a, b):
        self.a = a
        self.b = b
        if func == "add":
        elif func == "sub":
        elif func == "mul":
        elif func == "div":
    def add(self):
        print (self.a,"+",self.b,"=",self.a + self.b)
    def sub(self):
          print (self.a,"-",self.b,"=",self.a - self.b)
    def mul(self):
          print (self.a,"*",self.b,"=",self.a* self.b)
    def div(self):
        print (self.a,"/",self.b,"=",self.a / self.b)
cal = calc()
cal.execute("div", 6, 3)

More information about the Python-list mailing list