首页 > 解决方案 > Python:指定与继承一起使用的类方法的返回类型

问题描述

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

假设我有:

class Parent:

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


class Child(Parent):
    pass

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

提前致谢!

标签: pythoninheritancetypingclass-method

解决方案


现在有支持的语法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

推荐阅读