我希望获得每个类中的所有类名称和字段给定一个python文件说myFile.py。有没有办法实现这一目标?我想传入myFile.py并获得结果。
答案 0 :(得分:0)
您是否考虑过使用内置的抽象语法树(ast
)模块解析Python文件,然后检查结果以检索感兴趣的数据?简单的事情:
import ast
def print_info(path):
with open(path, "r") as src:
compiled = ast.parse(src.read(), "<string>", "exec")
for element in compiled.body:
if isinstance(element, ast.ClassDef): # we're interested only in classes
fields = []
methods = []
for field in element.body: # iterate over the class fields/methods
if isinstance(field, ast.Assign): # field assignment
for target in field.targets: # value can be assigned to many fields
fields.append(target.id)
elif isinstance(field, ast.FunctionDef): # method definition
methods.append(field.name)
# etc.
print("Class: " + element.name)
print("\tFields: " + ", ".join(fields))
print("\tMethods: " + ", ".join(methods))
满足您的主要要求。例如,如果我们有一个python源文件myFile.py
包含:
class A(object):
name = "A"
def __init__(self, x):
self.x = x
class B(object):
name = "B"
kind = "Child"
def instance_method(self):
pass
@classmethod
def class_method(cls):
pass
@staticmethod
def static_method():
pass
我们可以使用上面的内容轻松解析它:
print_info("myFile.py")
输出看起来像:
Class: A Fields: name Methods: __init__ Class: B Fields: name, kind Methods: instance_method, class_method, static_method
检查ast
包的其余部分,看看你可以从中提取哪种数据(提示:大部分)。