【问题标题】:Equivalent to super() for functools.singledispatch等效于 functools.singledispatch 的 super()
【发布时间】:2014-08-29 04:06:52
【问题描述】:

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'].

【问题讨论】:

    标签: python python-3.x super method-resolution-order functools


    【解决方案1】:

    我相信这样的东西会起作用,但我无法测试它,因为我没有安装 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,但真正的调度函数实际上可能会对该值执行某些操作,因此您需要将该值作为参数传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      • 2021-09-22
      • 1970-01-01
      • 2012-02-18
      • 2017-06-20
      相关资源
      最近更新 更多