相当于functools.singledispatch

2024-10-05 14:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

^{}帮助定义单个分派泛型方法。同时,^{}用于调用方法或访问超类的属性。在

有没有类似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'].

Tags: 方法registerdefault分派hellobasereturn定义
1条回答
网友
1楼 · 发布于 2024-10-05 14:27:21

我相信类似这样的东西会起作用,但我无法测试,因为我没有安装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()))

请注意,用超类作为参数调用hello是没有意义的,因为如果这样做,将丢失传递的原始参数(value)。在您的例子中,这并不重要,因为您的函数根本不使用value,但真正的调度函数可能实际会对该值执行某些操作,因此您需要将该值作为参数传递。在

相关问题 更多 >