<h4>不是理想的方法
<p>由于您引用的是类<code>A</code>中定义的方法,因此必须使用<code>@A.handle.register</code>来指示它:</p>
<pre><code>class B(A):
@A.handle.register
def handle_int(arg: int):
return arg + 2
</code></pre>
<h5>问题</h5>
<p>但是,当存在另一个类<code>C</code>时,这种方法会导致问题,该类也继承自<code>A</code>,但支持<code>handle(arg: str)</code>。然后<code>C().handle(2)</code>将从类<code>B</code>调用方法,因为它已注册到<code>A</code>方法(即使它最终应该是类<code>A</code>基句柄方法)</p>
<h4>更好的方法</h4>
<p>上述解决方案的明显问题是一个注册类(<code>A</code>),因此我将在所有派生类中添加注册,但如果派生类中没有适当的类型专用类方法,则将处理留给基类</p>
<pre><code>import functools
class A:
@functools.singledispatchmethod
def handle(arg):
print(f'\tA handle (arg: {arg})')
class B(A):
@functools.singledispatchmethod
@classmethod
def handle(cls, arg):
print(f'\tB handle (arg: {arg})')
return super(B, cls).handle(arg)
@B.handle.register
def handle_int(arg: int):
print(f'\tB int (arg: {arg})')
return arg + 2
class C(A):
@functools.singledispatchmethod
@classmethod
def handle(cls, arg):
print(f'\tC handle (arg: {arg})')
return super(C, cls).handle(arg)
@C.handle.register
def handle_str(arg: str):
print(f'\tC str (arg: {arg})')
return arg + ' 2'
print('\nA')
A.handle(2)
A.handle('2+')
print('\nB')
B.handle(2)
B.handle('2+')
print('\nC')
C.handle(2)
C.handle('2+')
</code></pre>
<p>结果:</p>
<pre><code>A
A handle (arg: 2)
A handle (arg: 2+)
B
B int (arg: 2)
B handle (arg: 2+)
A handle (arg: 2+)
C
C handle (arg: 2)
A handle (arg: 2)
C str (arg: 2+)
</code></pre>