29

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

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

4

3 回答 3

30

dummy.func1unbound,因此只需要一个显式self参数:

def greet(f,name):
    d = dummy()
    f(d, name)

greet(dummy.func1,'Bala')
于 2012-04-16T20:50:16.460 回答
8

由于dummy是类名,dummy.func1是未绑定的。

正如 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')
于 2015-11-30T18:23:45.927 回答
-1

你可以使用这样的东西:

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

这完美地工作:在键盘上

于 2012-04-16T20:52:46.567 回答