python - 如何制作类型提示前向引用

标签 python python-3.5 type-hinting

<分区>

我正在研究 python 的 3.5 类型提示。我想知道如何键入提示类方法的返回类型。

这是我的想法:

>>> class A():
    @classmethod
    def a(cls) -> A:
        pass

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    class A():
  File "<pyshell#24>", line 3, in A
    def a(cls) -> A:
NameError: name 'A' is not defined

显然它不起作用。我想一种方法是像这样进行某种“前向声明”:

>>> class A():
    pass

>>> class A():
    @classmethod
    def a(cls) -> A:
        pass

但这并不让人觉得“pythonic”。人们通常如何解决这个问题?

最佳答案

Forward references When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

https://www.python.org/dev/peps/pep-0484/#forward-references

PEP 文本继续提供以下示例:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

除了提供字符串之外,您提出的解决方法还有一个问题 - 如果您这样做:

class A():
    pass

class A():
    @classmethod
    def a(cls) -> A:
        pass

在(最终的和真实的)类 A 中注释的返回值是在处理类主体时携带 A 名称的对象 - 并且该对象是 stub A 类。因此,任何在静态或运行时分析中检查 A.a() 返回值的工具都会发现它不等于类 A

所以,如果需要解决这个问题(我曾经需要它,我忘记了上下文 - 它与注释无关 - 啊 - 我现在想起来了:它在一个自动生成 Python ctypes 的项目中特定 C 库的包装器),要走的路是创建一个单一的类,然后用赋值语句扩充它。对于您的示例,这将是:

class A:
    pass

def a(self) -> A:
    pass

A.a = a
del a

关于python - 如何制作类型提示前向引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36075276/

相关文章:

Python脚本从终端输入指定数量的元素

python - 如何填充 kinect v1 深度图像中的黑色补丁

python - 如何从 process.Popen() 引发事件 getche() - 不监视标准输入

python - 如何在 Python 3 中解析字节串?

python - 使用嵌套的 weakref 创建类实例的深拷贝

python - 以与 Python 2.7 和 Python 3.5 兼容的方式使用 abc.ABCMeta

python - type() 函数没有为 boto3 sqs 对象返回正确的结果?

python - isinstance 如何为 List 工作?

python - 创建字典,其中键来自列表,值是另一个列表中相应元素的总和

带有 Pandas 的 Python 类型提示?