使用Anytree类时未定义名称

时间:2017-06-16 14:13:54

标签: python anytree

我正在使用Python的anytree包,我正在尝试迭代树:

from anytree import Node, RenderTree, AsciiStyle

f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)

print(RenderTree(f, style=AsciiStyle()).by_attr())


for node in LevelOrderIter(f):
    print node.name

但是,出于某种原因,我收到错误NameError: name 'LevelOrderIter' is not defined

我已经安装了anytree(它可以创建节点等),根据语法我似乎是正确的:http://anytree.readthedocs.io/en/latest/apidoc/anytree.iterators.html#anytree.iterators.LevelOrderIter

任何想法它不起作用?

完整错误:

f
+-- b
    +-- a
Traceback (most recent call last):
  File "aa.py", line 10, in <module>
    for node in LevelOrderIter(f):
NameError: name 'LevelOrderIter' is not defined

2 个答案:

答案 0 :(得分:2)

如果您正在从库中调用函数,则可以将其称为anytree.LevelOrderIter()之类的库,或者您可以直接导入它:

from anytree import LevelOrderIter

答案 1 :(得分:0)

正确的示例如下所示(文档将在下一个版本中修复)

from anytree import Node, RenderTree, AsciiStyle, LevelOrderIter

f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)

print(RenderTree(f, style=AsciiStyle()).by_attr())


for node in LevelOrderIter(f):
    print node.name