How to pass a method as argument?

Edmondo Giovannozzi edmondo.giovannozzi at gmail.com
Thu Sep 30 06:28:00 EDT 2021


Il giorno giovedì 30 settembre 2021 alle 07:11:28 UTC+2 anila... at gmail.com ha scritto:
> 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)

For example:

|    def ex(self, fun):
|        getattr(self, fun)()


More information about the Python-list mailing list