动态分派,带有作为参数传入的函数

时间:2018-10-10 02:09:37

标签: python polymorphism dynamic-dispatch

示例

class Parent:

  def foo(self):
    print('parent')


class DerivedA(Parent):

  def foo(self):
    print('derived A')


class DerivedB(Parent):

  def foo(self):
    print('derived B')

def bar(passed_in_func):
  temp = [DerivedA(), DerivedB()]
  for derived in temp:
    passed_in_func(derived)

bar(Parent.foo)

输出:

parent
parent

所需的输出:

derived A
derived B

是否可以通过以下约束来调用派生类的函数bar

  1. Parent有多个派生类

  2. bar()不一定知道传入的是哪个派生类

  3. bar()的调用者将不知道要传入哪个派生类函数签名

编辑

我知道执行此操作的一种方法,但我认为它有点hacky:

def bar(passed_in_func):
  temp = [DerivedA(), DerivedB()]
  for derived in temp:
    getattr(derived, passed_in_func)()

bar('foo')

1 个答案:

答案 0 :(得分:0)

这是一种适用于直接子类的通用方法:

class Parent:
    def foo(self):
        print('parent')


class DerivedA(Parent):
    def foo(self):
        print('derived A')


class DerivedB(Parent):
    def foo(self):
        print('derived B')


def bar(passed_in_func):
    classname = passed_in_func.__qualname__.split('.')[0]
    parent = eval(classname)
    for derived in parent.__subclasses__():
        getattr(derived(), passed_in_func.__name__)()

bar(Parent.foo)

输出:

derived A
derived B