Python:指定类方法的返回类型,与继承一起使用。

问题描述 投票:0回答:1

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

假设我有。

class Parent:

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


class Child(Parent):
    pass

我应该指定什么作为 a_class_method 如果我想它是 Parent 为父母和 Child 为了孩子?我也试过 __qualname__但这似乎也不行。我是否应该不注释返回类型?

先谢谢你

python inheritance typing class-method
1个回答
2
投票

现在有支持的语法了,通过注释 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
© www.soinside.com 2019 - 2024. All rights reserved.