min*_*hee 8 python super method-resolution-order python-3.x functools
functools.singledispatch
有助于定义单调度泛型方法.同时,还有super()
调用方法或访问超类的属性.
是否有类似的东西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'].
Run Code Online (Sandbox Code Playgroud)
我相信这样的东西会起作用,但我无法测试它,因为我没有安装Python 3.4:
def getsuperclass(cls):
try:
nextclass = cls.__mro__[1]
except IndexError:
raise TypeError("No superclass")
return nextclass
@singledispatch
def hello(value):
return ['default']
@hello.register(Base)
def hello_base(value):
return hello.dispatch(getsuperclass(Base))(value) + ['base']
@hello.register(Derived)
def hello_derived(value):
return hello.dispatch(getsuperclass(Derived))(value) + ['derived']
print(hello(Derived()))
Run Code Online (Sandbox Code Playgroud)
hello
请注意,使用超类作为参数进行调用实际上没有意义,因为如果这样做,您将丢失value
传递的原始参数 ( )。在您的情况下,这并不重要,因为您的函数value
根本不使用,但真正的调度函数实际上可能会对该值执行某些操作,因此您需要将该值作为参数传递。
归档时间: |
|
查看次数: |
181 次 |
最近记录: |