使用 Python 的 ast 从类中获取属性



>我正在尝试使用 ast 打开一个.py文件,对于文件中的每个类,给我所需的属性。

但是,我无法让 ast 按预期行事。

我希望能够做到

import ast
tree = ast.parse(f)
for class in tree:
    for attr in class:
        print class+" "+attr.key+"="+attr.value

例如;有点像带有XML的ElementTree。 或者,也许我在ast背后有一个完全错误的想法,在这种情况下,是否可以以另一种方式做到这一点(如果没有,我会写一些东西来做到这一点)。

比这复杂一点。 您必须了解 AST 的结构和所涉及的 AST 节点类型。 此外,使用 NodeVisitor 类。 尝试:

import ast
class MyVisitor(ast.NodeVisitor):
    def visit_ClassDef(self, node):
        body = node.body
        for statement in node.body:
            if isinstance(statement, ast.Assign):
                if len(statement.targets) == 1 and isinstance(statement.targets[0], ast.Name):
                    print 'class: %s, %s=%s' % (str(node.name), str(statement.targets[0].id), str(statement.value))
tree = ast.parse(open('path/to/your/file.py').read(), '')
MyVisitor().visit(tree)

有关更多详细信息,请参阅文档。

最新更新