Variable annotations on a class

2019-08-19 03:35发布

问题:

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