在我的代码中,我有以下类:
class A:
@functools.singledispatchmethod
def handle(arg):
pass
我希望其他类从A
继承并重载泛型方法handle
,如下所示:
class B(A):
@handle.register
def handle_int(arg: int):
return arg + 2
但是,我得到一个错误:
unresolved reference 'handle'
如何在基类中创建此泛型方法?(我不想在每个子类中创建这个函数来使用singledispatchmethod
。)
要在Python中实现您想要做的事情有点困难}本身都是该语言中相对较新的特征。据我所知,目前还没有特别支持更复杂的重载,例如您正在尝试的重载
singledispatch
和{话虽如此,您可以使用第三方
multipledispatch
module尝试下面的方法。不过,这感觉有点像黑客,我不知道如何让它在类方法上工作——下面的解决方案只对实例方法有效使用pip上的另一个第三方模块
plum-dispatch
module,您可能会更接近您想要的结果。我对它了解不多,但我认为它有一些multipledispatch
没有的额外特性不是理想的方法
由于您引用的是类
A
中定义的方法,因此必须使用@A.handle.register
来指示它:问题
但是,当存在另一个类
C
时,这种方法会导致问题,该类也继承自A
,但支持handle(arg: str)
。然后C().handle(2)
将从类B
调用方法,因为它已注册到A
方法(即使它最终应该是类A
基句柄方法)更好的方法
上述解决方案的明显问题是一个注册类(
A
),因此我将在所有派生类中添加注册,但如果派生类中没有适当的类型专用类方法,则将处理留给基类结果:
相关问题 更多 >
编程相关推荐