31

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

3 Answers 3

32

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') 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. btw, what is unbound method?
It's a method that has no object associated to it. For more information, refer to this stackoverflow question
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') 

Comments

-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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.