使用 Python ast 模块访问语法树中的节点
我正在玩 python ast(抽象语法树)。
我编写了以下内容,它访问了 AST 的所有节点。
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
print 'Name :', node.id
def visit_Num(self, node):
print 'Num :', node.__dict__['n']
def visit_Str(self, node):
print "Str :", node.s
if __name__ == '__main__':
node = ast.parse("a = 1 + 2")
print ast.dump(node)
v = Py2Neko()
v.visit(node)
然后向 Py2Neko 类添加了一些方法,
def visit_Print(self, node):
print "Print :"
def visit_Assign(self, node):
print "Assign :"
def visit_Expr(self, node):
print "Expr :"
但是当它遇到“打印”语句或赋值或表达式时,它似乎停止并且不再继续。
它输出:
Module(body=[Assign(targets=[Name(id='a', ctx=Store())], value=BinOp(left=Num(n=1), op=Add(), right=Num(n=2)))])
Module
Assign :
有人能告诉我我做错了什么吗?
我正在使用Python 2.6.6
I'm playing with python ast (abstract syntax tree).
I wrote the following and it visited all nodes of the AST.
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
print 'Name :', node.id
def visit_Num(self, node):
print 'Num :', node.__dict__['n']
def visit_Str(self, node):
print "Str :", node.s
if __name__ == '__main__':
node = ast.parse("a = 1 + 2")
print ast.dump(node)
v = Py2Neko()
v.visit(node)
Then added some methods to Py2Neko class
def visit_Print(self, node):
print "Print :"
def visit_Assign(self, node):
print "Assign :"
def visit_Expr(self, node):
print "Expr :"
But then when it encounters a "print" statement or an assignement or an expression it seems that it stops and isn't going further.
It outputs:
Module(body=[Assign(targets=[Name(id='a', ctx=Store())], value=BinOp(left=Num(n=1), op=Add(), right=Num(n=2)))])
Module
Assign :
Can someone tell me what I did wrong.
I'm using Python 2.6.6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您的visit_Assign方法没有显式处理Assign节点的子节点,因此语法树的遍历到此为止。
如果您查看 ast.py 实现中的 NodeVisitor.generic_visit 方法,您会发现它循环遍历当前节点的子节点。因此,您可以从每个需要处理子项的方法中显式调用基类 generic_visit 方法:
Since your visit_Assign method does not explicitly process the child nodes of the Assign node, traversal of the syntax tree stops there.
If you have a look at the NodeVisitor.generic_visit method in the implementation of ast.py, you'll see that it loops through the children of the current node. So, you can explicitly call the base class generic_visit method from each of your methods that needs to process children:
对于非终端节点,您的访问函数必须访问子节点。请参阅如何使用 ast.NodeVisitor 的简单示例?更多信息。
For non-terminal nodes, your visit function has to visit the children. See Simple example of how to use ast.NodeVisitor? for some more information.