Python的:把当前类的返回类型注释 [英] Python: put current class as return type annotation

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

问题描述

在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

这code去与错误

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逆转(个体经营) - GT; 图:
这是可以理解的文档,虽然违反规则。缺点是,它不支持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.

推荐答案

所以,现在一段时间后,我可以说,我决定了用 - > 图表而不是 - >图。它不会让我的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.

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

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