Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass member function as argument in python?

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

like image 362
balki Avatar asked Apr 16 '12 20:04

balki


People also ask

Can you pass function as argument in Python?

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.

How do you send a function as an argument?

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.

How do I pass instance of an object as an argument in a function in Python?

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.


2 Answers

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') 
like image 115
phihag Avatar answered Oct 10 '22 23:10

phihag


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')
like image 31
jtpereyda Avatar answered Oct 10 '22 22:10

jtpereyda