2012-10-08 2 views
2

ast를 사용하여 .py 파일을 열고 파일의 각 클래스에 대해 원하는 속성을 지정하려고합니다.Python의 ast를 사용하여 클래스의 속성 얻기

그러나 예상대로 작동하지 않을 수 있습니다.

내가

예를 들어
import ast 

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

을 할 수 있기를 기대; XML로 ElementTree와 조금 비슷합니다. 아니면 ast의 뒤에 완전히 잘못된 생각을 가지고있을 수도 있습니다.이 경우에는 다른 방법으로이 작업을 수행 할 수 있습니까 (아니라면 내가 할 일을 작성합니다).

답변

1

조금 더 복잡합니다. 관련된 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을 참조하십시오.