30

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

balki
  • 26,394
  • 30
  • 105
  • 151

3 Answers3

30

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')
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 1
    Thanks. btw, what is unbound method? – balki Apr 16 '12 at 20:52
  • 1
    It's a method that has no object associated to it. For more information, refer to [this stackoverflow question](http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static) – phihag Apr 16 '12 at 20:54
10

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')
jtpereyda
  • 6,987
  • 10
  • 51
  • 80
-3

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

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • 1
    Yes this works but what I am trying to do is to pass the member function too as an argument. i.e `greet(dummy.func2,'Bala')` should also work – balki Apr 16 '12 at 20:55