将当前类作为返回类型注释 [英] putting current class as return type annotation

查看:28
本文介绍了将当前类作为返回类型注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 3 中,我可以创建参数并返回类型注释.示例:

In python 3 I can make arguments and return type annotations. Example:

class Graph:
    def __init__(self, V: int, E: int, edges: list):
        pass

    @classmethod
    def fromfile(cls, readobj: type(sys.stdin)):
        pass

    def V(self) -> int:
        pass

    def E(self) -> int:
        pass

问题是我无法使用当前类(Graph)的返回类型进行注释,该类型尚未定义.示例:

The problem is I can't make an annotation with return type of the current class (Graph), which is not defined yet. Example:

class Graph:
   def reverse(self) -> Graph:
       pass

此代码出错

def reverse(self) -> Graph:
NameError: name 'Graph' is not defined

这些注释对于记录和允许 IDE 识别参数和返回类型非常有用 => 启用自动完成

These annotations are really useful both for documenting and allowing IDE to recognize argument and return types => enable autocomplete

更新:所以我想到的是,这要么是不可能的,要么需要一些我不喜欢的技巧,所以我决定只使用 def reverse (self) ->'图表':这对于文档来说是可以理解的,尽管违反了规则.缺点是它不适用于 IDE 自动完成.

UPD: So what I came up is this is either impossible or requires some hacks I don't like, so I decided to use just def reverse (self) -> 'Graph': which is understandable for documentation although breaks the rule. The downside is that it doesn't work for IDE autocomplete.

推荐答案

所以现在过了一段时间我可以说我做出的决定是使用 ->'Graph' 而不是 ->图.它不会使我的 IDE (PyCharm) 能够以这种方式识别类型,但它仅适用于文档目的.

So now after a while I can say that decision I took was using -> 'Graph' instead of -> Graph. It does not make my IDE (PyCharm) able to recognize a type this way but it just works well enough for documentation purposes.

我可以使用的另一个可能的解决方案是在运行时更改注释,但这并不能解决文档问题——您不会想要在源代码中间的某个地方寻找类型声明...

Another possible solution I could use was changing annotation at runtime but that doesn't solve the problem with documentation - you won't want to look for type declarations somewhere in the middle of sources...

问题的根源在于在实际定义类之前识别类对象.这在 python 中是不可能做到的.

The problem has roots in recognizing class object before the class was actually defined. That is simply impossible to do in python.

这篇关于将当前类作为返回类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆