Python 3.5+ 中的递归类型 [英] Recursive Typing in Python 3.5+
问题描述
在 Python 3.5 中,添加了类型注释(请参阅此处).
In Python 3.5, type annotations were added (see here).
有没有办法定义递归类型的注解,比如树状结构?
Is there a way of defining recursive type annotations, such as for a tree-like structure?
class Employee(object):
def __init__(self, name: str, reports: List[Employee]):
self.name = name
self.reports = reports
在上面,注释 List[Employee]
似乎不起作用.运行代码导致此错误:
In the above, it doesn't seem as though the annotation List[Employee]
works. Running the code results in this error:
NameError: name 'Employee' 未定义
推荐答案
您可以使用 前向引用
通常发生这种情况的一种情况是定义容器类,其中定义的类出现在签名中的一些方法.例如下面的代码(开始的一个简单的二叉树实现)不起作用:
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']:
这篇关于Python 3.5+ 中的递归类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!