Gar*_*rwe 6 python type-hinting python-typing
使用PEP 484,有没有办法注释 classmethod 返回该类的实例?
例如
@dataclass
class Bar:
foo: str
@classmethod
def new_from_foo(cls, foo) -> Bar
...
Run Code Online (Sandbox Code Playgroud)
或者
@classmethod
def new_from_foo(cls, foo) -> cls
Run Code Online (Sandbox Code Playgroud)
诀窍是使用 aTypeVar将cls参数连接到返回注释:
from typing import TypeVar, Type
T = TypeVar('T')
class Bar:
@classmethod
def new_from_foo(cls: Type[T], foo) -> T:
...
Run Code Online (Sandbox Code Playgroud)