类上的变量注释 [英] Variable annotations on a class

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

问题描述

我正在尝试在某些代码中构建对象图,其中在Python 3.6中的类属性上使用类型提示.通常看起来像这样:

I'm trying to build up an object graph in some code where I'm using type hint on class attributes in Python 3.6. Generally this look like:

class MyObject:
    some_variable: float = 1.2

我的问题是我想拥有一个类型为MyObject的属性,如下所示:

My problem is that I would like to have an attribute that has a type MyObject like this:

class MyObject:
    parent: MyObject = None

当我尝试在注释上执行此操作时,出现"NameError:名称'MyObject'未定义".这似乎是目前无法成功的不受支持的边缘情况,因为在定义注释时MyObject并不完全存在.

When I try this I get "NameError: name 'MyObject' is not defined" when I try to do this on the annotation. This seems like an unsupported edge case that cannot currently succeed, since MyObject doesn't fully exist at the time the annotation is defined.

推荐答案

这可以使用转发参考.因此您的代码应如下所示:

This can be done using forward references. So your code would look like this:

class MyObject:
    parent: 'MyObject' = None

这篇关于类上的变量注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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