在Pydantic中,如何声明静态方法/类方法返回所讨论类的实例?

问题描述

我正在使用Python 3.7,并且具有类似的内容

class A(object):

  def __init__(self,value: int):
    self.value = value
  
  @classmethod
  def factory(cls,value: int) -> A:
    return A(value=value)

是的,这是一个人为的示例,但是我实质上是试图注释工厂函数以声明它返回了A的实例,但是,当我尝试运行flake8时,此方法将失败在文件上抱怨,因为它抱怨A未定义。

是否有某种方法可以对此功能进行注释,以使棉绒不会抱怨?

解决方法

您可以通过使用'A'进行注释来避免这种情况:

class A:
    @classmethod
    def factory(cls,value: int) -> 'A':
        ...

或者,您可以使用__future__ annotations

from __future__ import annotations

并继续使用A进行注释。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...