我正在玩 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
最佳答案
由于您的 visit_Assign 方法没有显式处理 Assign 节点的子节点,语法树的遍历到此为止。
如果您查看 ast.py 实现中的 NodeVisitor.generic_visit 方法,您会发现它循环遍历当前节点的子节点。因此,您可以从需要处理子项的每个方法中显式调用基类 generic_visit 方法:
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
def visit_Print(self, node):
print "Print :"
ast.NodeVisitor.generic_visit(self, node)
def visit_Assign(self, node):
print "Assign :"
ast.NodeVisitor.generic_visit(self, node)
def visit_Expr(self, node):
print "Expr :"
ast.NodeVisitor.generic_visit(self, node)
if __name__ == '__main__':
node = ast.parse("a = 1 + 2")
print ast.dump(node)
v = Py2Neko()
v.visit(node)
关于python - 使用 Python ast 模块访问语法树中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4947783/