Python - Class Generic Display Tool

Introduction

The following code displays class names and formats all attributes of an instance of any class.

Demo

class AttrDisplay: 
   def gatherAttrs(self): 
       attrs = [] #  w  w w.j  av  a 2s  .  c o m
       for key in sorted(self.__dict__): 
           attrs.append('%s=%s' % (key, getattr(self, key))) 
       return ', '.join(attrs) 

   def __repr__(self): 
       return '[%s: %s]' % (self.__class__.__name__, self.gatherAttrs()) 

if __name__ == '__main__': 

   class TopTest(AttrDisplay): 
       count = 0 
       def __init__(self): 
           self.attr1 = TopTest.count 
           self.attr2 = TopTest.count+1 
           TopTest.count += 2 
   class SubTest(TopTest): 
       pass 

   X, Y = TopTest(), SubTest()      # Make two instances 
   print(X)                         # Show all instance attrs 
   print(Y)                         # Show lowest class name

Result

Related Topic