在 Python 3.8 中,创建了一个用于创建多态函数的新装饰器 @singledispatchmethod,它根据提供的类型提示将 Python 重定向到方法的正确实现。
但是,我似乎无法使用打字模块中的复杂类型,您能告诉我我的示例有什么问题吗?
from typing import List
from functools import singledispatchmethod
class test:
@singledispatchmethod
def a(self, a):
return NotImplemented
@a.register
def _(self, a : str):
print(type(a))
# Uncomment to run the example
# @a.register
# def _(self, a: List[str]):
# print(type(a))
def b(self, b: List[str]):
print(type(b))
test().a(["A"])
test().b(["A"])
Run Code Online (Sandbox Code Playgroud)
如果第二个下划线函数的注释被取消注释,则 a 函数会出现以下错误,即使 b 函数不会出现以下错误:
TypeError: Invalid annotation for 'a'. typing.List[str] is not a class.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我正在尝试使用 python 3.8 的新功能之一(当前使用 3.8.3)。按照文档,我尝试了文档中提供的示例:
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
@classmethod
def neg(cls, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
@classmethod
def _(cls, arg: int):
return -arg
@neg.register
@classmethod
def _(cls, arg: bool):
return not arg
Negator.neg(1)
Run Code Online (Sandbox Code Playgroud)
但是,这会产生以下错误:
...
TypeError: Invalid first argument to `register()`: <classmethod object at 0x7fb9d31b2460>. Use either `@register(some_class)` or plain `@register` on an annotated function.
Run Code Online (Sandbox Code Playgroud)
如何创建泛型类方法?我的示例中是否缺少某些内容?
更新:
我已经阅读了 Aashish A 的回答,这似乎是一个持续存在的问题。我设法通过以下方式解决了我的问题。
...
TypeError: Invalid first argument to `register()`: <classmethod object at 0x7fb9d31b2460>. Use …
Run Code Online (Sandbox Code Playgroud)