2016-07-13 18 views
3

In Python 3.5 wurden Typ Anmerkungen hinzugefügt (siehe here).Rekursive Typisierung in Python 3.5+

Gibt es eine Möglichkeit, rekursive Annotationen zu definieren, z. B. für eine baumartige Struktur?

class Employee(object): 
    def __init__(self, name: str, reports: List[Employee]): 
     self.name = name 
     self.reports = reports 

Im obigen es scheint nicht, als ob die Anmerkung List[Employee] funktioniert. Ausführen der Code führt diesen Fehler:

NameError: name 'Employee' is not defined

Antwort

8

Sie Forward References in PEP 484 definiert

A situation where this occurs commonly is the definition of a container class, where the class being defined occurs in the signature of some of the methods. For example, the following code (the start of a simple binary tree implementation) does not work:

class Tree: 
    def __init__(self, left: Tree, right: Tree): 
     self.left = left 
     self.right = right 

To address this, we write:

class Tree: 
    def __init__(self, left: 'Tree', right: 'Tree'): 
     self.left = left 
     self.right = right 

It is allowable to use string literals as part of a type hint, for example:

class Tree: 
    ... 
    def leaves(self) -> List['Tree']: 
verwenden können