[英]How to specify the return type of parent method as the child class dynamically using python type hinting?
[英]Python: specify return type of class method that works with inheritance
我一直试图了解如何在 Python 中指定 class 方法的返回类型,以便即使对于子类也能正确解释(例如在我的 Sphinx 文档中)。
假设我有:
class Parent:
@classmethod
def a_class_method(cls) -> 'Parent':
return cls()
class Child(Parent):
pass
如果我希望它是Parent
级的父级和Child
级的子级,我应该指定什么作为a_class_method
的返回类型? 我也尝试过__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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.