带有作为参数传入的函数的动态调度
Dynamic Dispatch with a function passed in as a parameter
例子
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
有没有什么方法可以使用以下约束调用派生的 class' 函数 bar
?
有多个派生的 class 来自 Parent
bar()
不一定知道派生的 classes 中传入了哪个
bar()
的调用者将不知道要传入哪个派生的 class 函数签名
编辑
我知道有一种方法可以做到这一点,但我认为它有点老套:
def bar(passed_in_func):
temp = [DerivedA(), DerivedB()]
for derived in temp:
getattr(derived, passed_in_func)()
bar('foo')
这是一种适用于直接子类的通用方法:
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
例子
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
有没有什么方法可以使用以下约束调用派生的 class' 函数 bar
?
有多个派生的 class 来自 Parent
bar()
不一定知道派生的 classes 中传入了哪个bar()
的调用者将不知道要传入哪个派生的 class 函数签名
编辑
我知道有一种方法可以做到这一点,但我认为它有点老套:
def bar(passed_in_func):
temp = [DerivedA(), DerivedB()]
for derived in temp:
getattr(derived, passed_in_func)()
bar('foo')
这是一种适用于直接子类的通用方法:
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