Python AST:如何获取节点的子节点
我正在使用Python 2.6.5 给定一个抽象语法树,我想获取它的子级 大多数StackOverflow帖子都讨论了Python AST:如何获取节点的子节点,python,abstract-syntax-tree,Python,Abstract Syntax Tree,我正在使用Python 2.6.5 给定一个抽象语法树,我想获取它的子级 大多数StackOverflow帖子都讨论了ast.NodeVisitor以及其中定义的方法:visit(),generic\u visit()。 但是,visit()和generic\u visit()不会给孩子们,而是直接对他们递归地应用函数 有人能写一个简短的代码来演示一下吗? python库中是否存在相同的预定义函数?包含节点子节点的附件取决于节点表示的语法类型。每个节点类还具有一个特殊的\u fields属性,该
ast.NodeVisitor
以及其中定义的方法:visit()
,generic\u visit()
。
但是,visit()
和generic\u visit()
不会给孩子们,而是直接对他们递归地应用函数
有人能写一个简短的代码来演示一下吗?
python库中是否存在相同的预定义函数?包含节点子节点的附件取决于节点表示的语法类型。每个节点类还具有一个特殊的
\u fields
属性,该属性列出了该类具有的子节点的属性名称。比如说,
>>> ast.parse('5+a')
<_ast.Module object at 0x02C1F730>
>>> ast.parse('5+a').body
[<_ast.Expr object at 0x02C1FF50>]
>>> ast.parse('5+a').body[0]
<_ast.Expr object at 0x02C1FBF0>
>>> ast.parse('5+a').body[0]._fields
('value',)
>>> ast.parse('5+a').body[0].value
<_ast.BinOp object at 0x02C1FF90>
>>> ast.parse('5+a').body[0].value._fields
('left', 'op', 'right')
>>> ast.parse('5+a').body[0].value.left
<_ast.Num object at 0x02C1FB70>
如果我们查找BinOp的定义,我们会看到它有3个不同的参数,left,op和right。我希望您能够从这里开始。ast模块提供了一个您可能会发现有用的
iter\u子节点
功能
def iter_child_nodes(node):
"""
Yield all direct child nodes of *node*, that is, all fields that are nodes
and all items of fields that are lists of nodes.
"""
for name, field in iter_fields(node):
if isinstance(field, AST):
yield field
elif isinstance(field, list):
for item in field:
if isinstance(item, AST):
yield item
`
谢谢你的回复!但是我还没有完全理解。。。那么node.\u字段将给出该特定节点的子节点?(以元组的形式?)。。。。那么身体和价值意味着什么呢?谢谢你的帮助!
>>> ast.parse('5+a')._fields
('body',)
>>> ast.parse('5+a').body
[<_ast.Expr object at 0x02E965B0>]
>>> ast.parse('5+a').body[0].value
<_ast.BinOp object at 0x02E96330>
def iter_child_nodes(node):
"""
Yield all direct child nodes of *node*, that is, all fields that are nodes
and all items of fields that are lists of nodes.
"""
for name, field in iter_fields(node):
if isinstance(field, AST):
yield field
elif isinstance(field, list):
for item in field:
if isinstance(item, AST):
yield item
`