Variable annotations on a class

2019-08-19 03:32发布

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.

2条回答
Anthone
2楼-- · 2019-08-19 03:47

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

class MyObject:
    parent: 'MyObject' = None
查看更多
混吃等死
3楼-- · 2019-08-19 04:01

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
查看更多
登录 后发表回答