我正在尝试使用 ast 打开一个 .py 文件,并为文件中的每个类提供我想要的属性。
但是,我无法像预期的那样表现。
我希望能够做到
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)
参见 the docs了解更多详情。
