python编译器包说明

里奥内尔319

我进行了艰苦的搜索,但几乎找不到有关如何使用python编译器软件包(https://docs.python.org/2/library/compiler.html)以及如何创建可输入到的游客类的任何信息。编译器步行(https://docs.python.org/2/library/compiler.html#compiler.walk)方法。

有谁可以帮助我吗?提前致谢。

sepp2k

通过定义的子类,compiler.visitor.ASTVisitor然后visitXXX为要您的访问者处理的每种节点类型定义一个方法创建访问者类XXX节点类型的名称在哪里-可能的节点类型在文档的表中列出)您已链接)。

任何此类方法都self将带有一个参数(如果为,则为两个),它将是表示已访问节点的节点对象。该对象上可用的属性也在表中列出。如果希望访问者进一步进入树中,则应visit在该节点的每个子节点上调用

在compiler.visitor.walk()方法中,它接受两个参数,tree和visitor。那些是什么?

tree是您要处理的AST,并且visitor是您创建用来处理AST的visitor类的实例。

我怎么能得到那些呢?

您可以通过调用compiler.parse一些Python源代码来获取AST,并通过编写一个visitor类并创建一个实例来获取visitor。

这是一个使用访客的示例,该访客仅计算一段Python代码中的加法运算符的数量:

import compiler

class PlusCounter(compiler.visitor.ASTVisitor):
    def __init__(self):
        self.count = 0

    def visitAdd(self, node):
        self.count += 1
        self.visit(node.left)
        self.visit(node.right)

plus_counter = PlusCounter()
compiler.walk(compiler.parse("1 + 2 * (3 + 4)"), plus_counter)
print(plus_counter.count)

这是使用不推荐使用的ast的相同示例,其工作方式基本上相同,但是AST结构略有不同。与上面的代码不同,此代码实际上将在Python 3中工作:

import ast

class PlusCounter(ast.NodeVisitor):
    def __init__(self):
        self.pluses = 0

    def visit_Add(self, node):
        # We don't need to visit any child nodes here because in the ast package
        # the AST is structured slightly differently and Add is merely a child
        # node of the BinOp node, which holds the operands. So Add itself has
        # no children that need to be visited
        self.pluses += 1

plus_counter = PlusCounter()
plus_counter.visit(ast.parse("1 + 2 * (3 + 4)"))
print(plus_counter.pluses)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章