How to pass a method as argument?
Avi Gross
avigross at verizon.net
Thu Sep 30 17:11:21 EDT 2021
Sounds like an excellent homework question.
But your method of using an object is not what first comes to mind based on
your cursory description.
There is a python idiom using functional programming that looks like this:
def doit(a, b, fun): return(fun(a,b))
So make up your own functions like:
def addit(a,b): return(a+b)
And make up others doing multiply and whatever and call something like this:
doit(3,5, addit)
Now if you want a user to put in text like "add" that is another story. If
you want this in the context of an object, ditto.
-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of Anil Anvesh
Sent: Thursday, September 30, 2021 1:11 AM
To: python-list at python.org
Subject: How to pass a method as argument?
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)
--
https://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list