How to pass a method as argument?

Anil Anvesh anilanvesh at gmail.com
Thu Sep 30 01:11:16 EDT 2021


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)


More information about the Python-list mailing list