Variable annotations on a class

隐身守侯 提交于 2019-12-24 18:29:45

问题


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

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

class MyObject:
    parent: MyObject = None

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.


回答1:


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

class MyObject:
    parent: 'MyObject' = None



回答2:


This seem to be hacky and is probably not the desired way to do this, but you can define MyObject with

class MyObject:
    pass

and redefine MyObject as:

class MyObject:
    parent: MyObject = None


来源:https://stackoverflow.com/questions/46605651/variable-annotations-on-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!