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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (164)

我想传递类似于成员函数指针的内容。我试过以下几种方法。

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

提问于
用户回答回答于
def greet(f,name):
    d = dummy()
    f(d, name)

greet(dummy.func1,'Bala')
用户回答回答于
def greet(f,name):
    d = dummy()
    f(d, name)

greet(dummy.func1, 'Bala')

或者,您可以实例化dummygreet:

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

扫码关注云+社区

领取腾讯云代金券