^{
有没有类似super()
的东西可以与singledispatch
一起使用吗?我尝试了以下操作,但是super(Derived, value)
的结果只是不是Base
的实例,因此它并不像我预期的那样工作:
from functools import singledispatch
@singledispatch
def hello(value):
return ['default']
@hello.register(Base)
def hello_base(value):
return hello(super(Base, value)) + ['base']
@hello.register(Derived)
def hello_derived(value):
return hello(super(Derived, value)) + ['derived']
print(hello(Derived())
# expected ['default', 'base', 'derived'],
# but actually is ['default', 'derived'].
我相信类似这样的东西会起作用,但我无法测试,因为我没有安装Python 3.4:
请注意,用超类作为参数调用
hello
是没有意义的,因为如果这样做,将丢失传递的原始参数(value
)。在您的例子中,这并不重要,因为您的函数根本不使用value
,但真正的调度函数可能实际会对该值执行某些操作,因此您需要将该值作为参数传递。在相关问题 更多 >
编程相关推荐