考虑一对在Python中表示相同事物的类,每个类都实现了将一个类转换为另一个类的方法.例如,考虑将笛卡尔坐标转换为极坐标,反之亦然.

@dataclass
class CartesianCoordinates:
  x: float
  y: float
  
  def toPolarCoordinates(self) -> PolarCoordinates:
      radius = ...
      theta = ...
      result = PolarCoordinates(radius, theta)
      return result
  

@dataclass
class PolarCoordinates:
  radius: float
  theta: float

  def toCartesianCoordinates(self) -> CartesianCoordinates:
    x = ...
    y = ...
    result = CartesianCoordinates(x,y)
    return result

因为我在定义它之前使用了PolarCoordinates,所以我try 通过在CartesianCoordinates定义之前插入以下行来转发(实际上重新定义)它的声明:

class PolarCoordinates:
    # forwarding declaration
    pass

这是可行的,从这个意义上讲,代码可以正确运行,但是像mypy这样的判断将会失败,因为类重新定义会出现类似Name PolarCoordinates already defined的错误.

我知道用Python语言进行真正的向前声明是不可能的,但是有没有什么等价的东西允许在类完全定义之前引用它,并且允许S像mypy一样判断通过呢?

推荐答案

Python支持正向类型声明.您可以使用字符串:

    def toPolarCoordinates(self) -> 'PolarCoordinates':

或从future 进口(不需要DeLorean):

from __future__ import annotations

…

    def toPolarCoordinates(self) -> PolarCoordinates:

Python相关问答推荐

大Pandas 胚胎中产生组合

acme错误-Veritas错误:模块收件箱没有属性linear_util'

Pandas 有条件轮班操作

可变参数数量的重载类型(args或kwargs)

将输入管道传输到正在运行的Python脚本中

如何找到满足各组口罩条件的第一行?

如何更改分组条形图中条形图的 colored颜色 ?

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

优化器的运行顺序影响PyTorch中的预测

在极性中创建条件累积和

Pandas Data Wrangling/Dataframe Assignment

Pandas:计算中间时间条目的总时间增量

为什么'if x is None:pass'比'x is None'单独使用更快?

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

从源代码显示不同的输出(机器学习)(Python)

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

来自Airflow Connection的额外参数

使用美汤对维基百科表格进行网络刮擦未返回任何内容

Django REST框架+Django Channel->;[Errno 111]连接调用失败(';127.0.0.1';,6379)

如何在微调Whisper模型时更改数据集?