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

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

问题描述

在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

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

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

UPD: 所以我想到的是这是不可能的,或者需要一些我不喜欢的技巧,所以我决定只使用def reverse (self) -> 'Graph': 尽管违反了规则,但对于文档来说是可以理解的.缺点是它不适用于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'而不是-> 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天全站免登陆