balki
balki

Reputation: 27684

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

Upvotes: 31

Views: 29814

Answers (3)

jtpereyda
jtpereyda

Reputation: 7385

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')

Upvotes: 10

hjpotter92
hjpotter92

Reputation: 80649

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

Upvotes: -3

phihag
phihag

Reputation: 288090

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')

Upvotes: 32

Related Questions