<p>要在Python中实现您想要做的事情有点困难<code>singledispatch</code>和{<cd2>}本身都是该语言中相对较新的特征。据我所知,目前还没有<em>特别支持</em>更复杂的重载,例如您正在尝试的重载</p>
<p>话虽如此,您可以使用第三方<code>multipledispatch</code><a href="https://github.com/mrocklin/multipledispatch/" rel="nofollow noreferrer">module</a>尝试下面的方法。不过,这感觉有点像黑客,我不知道如何让它在类方法上工作——下面的解决方案只对实例方法有效</p>
<pre><code>from multipledispatch import dispatch
@dispatch(object, object)
def handle(instance, arg):
return 'Base implementation'
class A:
def handle(self, arg):
return handle(self, arg)
class B(A):
pass
class C(A):
pass
@dispatch(B, int)
def handle(instance, arg):
return 'Specialised implementation for class B and ints'
@dispatch(C, str)
def handle(instance, arg):
return 'Specialised implementation for class C and strs'
a, b, c = A(), B(), C()
print(a.handle('hi')) # prints "Base implementation"
print(b.handle('hi')) # prints "Base implementation"
print(b.handle(3)) # prints "Specialised implementation for class B and ints"
print(c.handle(3)) # prints "Base implementation"
print(c.handle('hi')) # prints "Specialised implementation for class C and strs"
</code></pre>
<p>使用pip上的另一个第三方模块<code>plum-dispatch</code><a href="https://github.com/wesselb/plum#comparison-with-multipledispatch" rel="nofollow noreferrer">module</a>,您可能会更接近您想要的结果。我对它了解不多,但我认为它有一些<code>multipledispatch</code>没有的额外特性</p>