Mar*_*ark 1 python inheritance typing class-method
我一直试图了解如何在 Python 中指定类方法的返回类型,以便即使对于子类也能正确解释(例如在我的 Sphinx 文档中)。
假设我有:
class Parent:
@classmethod
def a_class_method(cls) -> 'Parent':
return cls()
class Child(Parent):
pass
Run Code Online (Sandbox Code Playgroud)
a_class_method如果我希望它是Parent为父母和Child孩子的,我应该指定什么作为返回类型?我也试过__qualname__,但这似乎也不起作用。我应该不注释返回类型吗?
提前致谢!
现在有支持的语法,通过cls使用类型变量进行注释。引用 PEP 484 中的示例之一:
T = TypeVar('T', bound='C')
class C:
@classmethod
def factory(cls: Type[T]) -> T:
# make a new instance of cls
class D(C): ...
d = D.factory() # type here should be D
Run Code Online (Sandbox Code Playgroud)