键入注释稍后定义的类(正向引用) [英] Type annotating a class that is defined later (Forward Reference)

查看:49
本文介绍了键入注释稍后定义的类(正向引用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于样式原因,我试图在类Foo之前​​保留myDict的定义.因为尚未定义Foo,这将导致NameError.

For style reasons I'm trying to keep definition of myDict before class Foo. This will cause a NameError because Foo is not yet defined.

from typing import Dict

myDict: Dict[str, Foo] = {}

class Foo:
    pass

将myDict移到Foo下方显然可以解决此问题,但是有什么办法可以使myDict及其注释保持在顶部?

Moving myDict below Foo obviously fixes this, but is there any way I can keep myDict and its annotation up top?

推荐答案

您可以按如下所示对其进行引用:

You can quote it as follows:

from typing import Dict

myDict: Dict[str, 'Foo'] = {}

class Foo:
    pass

请参见 https://www.python.org/dev/peps/pep-0484/#forward-references 了解更多信息.

这篇关于键入注释稍后定义的类(正向引用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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