How to pass member function as argument in python?

Question:

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

Asked By: balki

||

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')
Answered By: phihag

You can use something like this:

class dummy:
  def func1(self,name):
      print 'hello %s' % name
  def func2(self,name):
      print 'hi %s' % name
def greet(name):
  d = dummy()
  d.func1(name)
greet('Bala')

and this works perfectly: on codepad

Answered By: hjpotter92

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')
Answered By: jtpereyda
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.