I want to pass something similar to a member function pointer. I tried the following.
class dummy:
def func1(self,name):
print 'hello %s' % name
def func2(self,name):
print 'hi %s' % name
def greet(f,name):
d = getSomeDummy()
d.f(name)
greet(dummy.func1,'Bala')
Expected output is hello Bala
In Python, just like a normal variable, we can pass a user-defined function as an argument to another function. A function that accepts another function as its parameter is called a Higher-order function.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
When you call an instance method (e.g. func ) from an instance object (e.g. inst ), Python automatically passes that instance object as the first argument, in addition to any other arguments that were passed in by the user.
dummy.func1
is unbound, and therefore simply takes an explicit self
argument:
def greet(f,name): d = dummy() f(d, name) greet(dummy.func1,'Bala')
Since dummy
is the class name, dummy.func1
is unbound.
As phihag said, you can create an instance of dummy
to bind the method:
def greet(f,name):
d = dummy()
f(d, name)
greet(dummy.func1, 'Bala')
Alternatively, you can instantiate dummy
outside of greet
:
def greet(f,name):
f(name)
my_dummy = dummy()
greet(my_dummy.func, 'Bala')
You could also use functools.partial
:
from functools import partial
def greet(f,name):
f(name)
my_dummy = dummy()
greet(partial(dummy.func1, my_dummy), 'Bala')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With