为类参数和返回值键入注释

时间:2020-04-30 17:48:18

标签: python python-3.x

假设我有以下内容:

from __future__ import annotations

class A(object):

    @classmethod
    def some_class_method(cls: ?, parameter: str) -> ?:
        return A

如果我想弄清楚?返回了some_class_method 不是A的实例。

编辑:@chepner提出了一个好的观点,即A可能是指? A 的任何子类。

1 个答案:

答案 0 :(得分:5)

您无法使用A,因为尚未定义。相反,您需要使用'A'。您还需要使用Type,因为'A'表示A的实例:

from typing import Type

class A(object):
    @classmethod
    def some_class_method(cls: Type['A'], parameter: str) -> Type['A']:
        return A