是否可以仅通过操作ast.NodeVisitor.generic_visit()在Python中的ast.NodeVisitor实例上进行后置遍历?我这样做:
class ExpParser(ast.NodeVisitor):
def generic_visit(self, node):
for x in ast.iter_child_nodes(node):
ast.NodeVisitor.generic_visit(self, x)
ast.NodeVisitor.generic_visit(self, node)
def visit_BinOp(self, node):
print type(node.op).__name__
def visit_Name(self, node):
print node.id
if __name__ == '__main__':
node = ast.parse("T1+T2*T3")
v = ExpParser()
v.visit(node)
这给了我:
T1
T2
T3
Mult
Add
我想要它给我:
T2
T3
Mult
T1
Add
我该怎么做?请卡住.
解决方法:
尝试这样的事情
import ast
class ExpParser(ast.NodeVisitor):
def generic_visit(self, node):
for field, value in reversed(list(ast.iter_fields(node))):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
self.visit(item)
elif isinstance(value, ast.AST):
self.visit(value)
def visit_BinOp(self, node):
self.generic_visit(node)
print type(node.op).__name__
def visit_Name(self, node):
self.generic_visit(node)
print node.id
if __name__ == '__main__':
node = ast.parse("T1+T2*T3")
v = ExpParser()
v.visit(node)
不要忘记在每个访问方法上调用generic_visit,或者重新实现访问方法以自动进行处理.