omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular
    1. Home
    2. Leeman

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    • Profile
    • Following 0
    • Followers 0
    • Topics 1
    • Posts 1
    • Best 0
    • Controversial 0
    • Groups 0

    Leeman

    @Leeman

    0
    Reputation
    388
    Profile views
    1
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    Leeman Unfollow Follow

    Latest posts made by Leeman

    • Accessing attributes of classes and methods in Python AST

      I have written some codes to count number of attributes in classes and methods of a module but I'm not getting results. I'll be glad to get assistance. Perhaps there's something I'm doing wrongly or not doing at all. Here's the codes:

      # To count the attributes in a Class and Method
      
      import ast
      
      
      class ClassAttributes(object):
          def __init__(self, node):
              self.node = node
              self.loc_in_module = 0
              self.loc_in_class = 0
      
          def get_attribute_names(self):
              for cls in self.node.body:
      
                  if isinstance(cls, ast.ClassDef):
                      self.loc_in_class += 1
                      print('Class {}'.format(self.loc_in_class))
      
                      self.loc_in_method = 0
                      if isinstance(cls, ast.Attribute) or isinstance(cls, ast.Assign):
                          
                          for target in target.targets:
                              print('{} Atrribute: {}'.format(str(cls.lineno), target))
      
                      for node in ast.walk(cls):
                          if isinstance(node, ast.FunctionDef):
                              self.loc_in_method += 1
                              print('Method {}'.format(self.loc_in_method))
                              if isinstance(node, ast.Attribute) or isinstance(node, ast.Assign):
                             
                                  for target in target.targets:
                                      print('{} Atrribute: {}'.format(str(node.lineno), target))
      
      
      if __name__ == '__main__':
          filename = 'test.py'
      
          with open(filename, 'r') as pyfile:
              data = pyfile.read()
              pyfile.close()
              tree = ast.parse(data)
      
      
          v = ClassAttributes(tree)
          v.get_class_attribute_names()
      
      posted in Pythonista
      Leeman
      Leeman