一次调度上调

时间:2019-09-30 20:02:08

标签: python super

我很好奇是否可以模拟super().method()的正常调用来调用“父母的” method(),但使用singledispatch而不是方法多态性。

据我所知,答案是“否”。我认为索引到MRO中不是可行的解决方案,但可能是错误的。

from functools import singledispatch

class A:
  pass

class B(A):
  pass

@singledispatch
def f(obj):
    raise NotImplementedError(obj)

@f.register(A)
def _(obj):
  print('A')

@f.register(B)
def _(obj):
  print('B')
  f.dispatch(super(B, obj))

b = B()
# I want this to print "B" then "A"
f(b)

输出

B
Traceback (most recent call last):
  File "main.py", line 29, in <module>
    f(b)
  File "/usr/local/lib/python3.7/functools.py", line 840, in wrapper
    return dispatch(args[0].__class__)(*args, **kw)
  File "main.py", line 24, in _
    f.dispatch(super(B, obj))
  File "/usr/local/lib/python3.7/functools.py", line 795, in dispatch
    impl = dispatch_cache[cls]
  File "/usr/local/lib/python3.7/weakref.py", line 396, in __getitem__
    return self.data[ref(key)]
TypeError: cannot create weak reference to 'super' object

0 个答案:

没有答案