键入提示 PyCharm 内部使用的类 [英] Typing hints PyCharm for a class used within itself

查看:51
本文介绍了键入提示 PyCharm 内部使用的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在类中正确键入类?在 PyCharm 中,我目前收到此错误:

How do I properly type a class within itself? In PyCharm I am currently getting this error:

这是一个未解决的参考错误.这通常是有道理的,因为我不希望 PyCharm 完美地支持类型.但是,当我在 Item 类本身之外的其他类中使用它时,没有错误:

This is an unresolved reference error. This normally makes sense because I wouldn't expect PyCharm to support types perfectly. However, when I use it in other classes besides the Item class itself there is no error:

因此我相信只有在其自己的类中提供类型提示时才会出现错误.所以我不知道究竟该怎么做才能防止这个错误,或者我是否使用了错误的类型,并且类型本身不应该被使用.

Thus I believe that the error only appears when the type hint is supplied within its own class. So I don't know what exactly to do to prevent this error or if I am using types wrong in general and a type shouldn't be used within itself.

基本上,我试图模仿的行为是您有一个物品的制作配方,并且可以使用配方功能创建该物品的新实例.

Basically the behavior I am trying to emulate is that you have a crafting recipe for an item and can create new instances of that item with the recipe function.

推荐答案

当使用类作为该类中的类型时,或在该类型尚未完全定义的任何地方,您需要将类型用单引号或双引号括起来在您的注释中:

When using a class as a type inside that class, or anywhere where that type is not fully defined yet, you need to enclose the type in single or double quotes in your annotations:

class Item:
    ...
    def craft(self, substrates: List['Item'], amount: int) -> List['Item']:
        ...

来源:

https://www.python.org/dev/peps/pep-0484/#forward-references

https://blog.jetbrains.com/pycharm/2015/11/python-3-5-type-hinting-in-pycharm-5/
(基于字符串的提示)

https://blog.jetbrains.com/pycharm/2015/11/python-3-5-type-hinting-in-pycharm-5/
(String-Based Hints)

编辑:PEP 563:https://www.python.org/dev/peps/pep-0563/ 对此进行了改进.

Edit: PEP 563: https://www.python.org/dev/peps/pep-0563/ improves upon this.

这篇关于键入提示 PyCharm 内部使用的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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