在我的代码中,我有以下课程:
class A:
@functools.singledispatchmethod
def handle(arg):
pass
我想要其他类继承A
并重载泛型方法handle
像这样:
class B(A):
@handle.register
def handle_int(arg: int):
return arg + 2
但是,我收到错误:
未解析的引用“句柄”
如何在基类中创建这个通用方法? (我不想在每个子类中创建这个函数来使用singledispatchmethod
.)
不理想的方法
由于您指的是类中定义的方法A
你必须使用来表明它@A.handle.register
:
class B(A):
@A.handle.register
def handle_int(arg: int):
return arg + 2
Issue
但是当存在另一个类时,这种方法会引起问题C
,也继承自A
但支持handle(arg: str)
. Then C().handle(2)
将从类中调用方法B
自从它被注册到A
方法(即使它应该最终出现在类中A
基本句柄方法)。
更好的方法
上述解决方案的明显问题是一个注册类(A
),所以我在所有派生类中添加注册,但将处理留给基类,以防派生类中没有适当的类型专用类方法。
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+')
Result:
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+)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)