如何在python中传递成员函数作为参数?

时间:2012-04-16 20:46:14

标签: python python-2.7

我想传递类似于成员函数指针的东西。我尝试了以下内容。

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

3 个答案:

答案 0 :(得分:25)

dummy.func1unbound,因此只需要一个明确的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