我想传递类似于成员函数指针的东西。我尝试了以下内容。
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')
预期输出为hello Bala
答案 0 :(得分:25)
dummy.func1
是unbound,因此只需要一个明确的self
参数:
def greet(f,name):
d = dummy()
f(d, name)
greet(dummy.func1,'Bala')
答案 1 :(得分:6)
由于dummy
是类名,dummy.fun1
是未绑定的。
正如phihag所说,你使用dummy
的实例绑定方法:
def greet(f,name):
d = dummy()
f(d, name)
greet(dummy.func1, 'Bala')
或者,您可以在dummy
之外实例化greet
:
def greet(f,name):
f(name)
my_dummy = dummy()
greet(my_dummy.func, 'Bala')
您也可以使用functools.partial
:
from functools import partial
def greet(f,name):
f(name)
my_dummy = dummy()
greet(partial(dummy.func1, my_dummy), 'Bala')
答案 2 :(得分:0)
您可以使用以下内容:
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')
这完美无缺:on codepad