Python:指定使用继承的类方法的返回类型



我一直在努力了解如何在Python中指定类方法的返回类型,以便即使对于子类也能正确解释(例如,在我的Sphinx文档中(。

假设我有:

class Parent:
@classmethod
def a_class_method(cls) -> 'Parent':
return cls()

class Child(Parent):
pass

如果我希望a_class_method的返回类型为Parent(对于父项(和Child(对于子项(,我应该指定什么作为返回类型?我也尝试过__qualname__,但似乎也不起作用。我应该不注释返回类型吗?

提前感谢!

现在有支持的语法,通过用类型变量注释cls。引用PEP484中的一个例子:

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

最新更新