Advertisement
Woobinda

Отображение дерева наследования класса

Dec 22nd, 2015
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.17 KB | None | 0 0
  1.  
  2. class ListInstance:
  3.     """
  4.     Примесный класс, реализующий получение форматированной строки при вызове
  5.     функций print() и str() с экземпляром в виде аргумента, через наследование
  6.     метода __str__, реализованного здесь; отображает только атрибуты
  7.     экземпляра; self – экземпляр самого нижнего класса в дереве наследования;
  8.     во избежание конфликтов с именами атрибутов клиентских классов использует
  9.     имена вида __X
  10.     """
  11.  
  12.     def __str__(self):
  13.         return '<Instance Of %s(%s), address %s:\n%s' % (
  14.             self.__class__.__name__,
  15.             self.supers(),
  16.             id(self),
  17.             self.__attrnames())
  18.  
  19.     def __attrnames(self):
  20.         result = ''
  21.         for attr in sorted(self.__dict__):
  22.             result += '\tname %s=%s\n' % (attr, self.__dict__[attr])
  23.         return result
  24.  
  25.     def supers(self):                               #Выводит имена суперклассов экземпляра.
  26.         supers = []
  27.         for cls in self.__class__.__bases__:
  28.             supers.append(cls.__name__)
  29.         return ', '.join(supers)
  30.  
  31.  
  32. class ListInherited:
  33.     """
  34.     Использует функцию dir() для получения списка атрибутов самого экземпляра
  35.     и атрибутов, унаследованных экземпляром от его классов
  36.     """
  37.     def __str__(self):
  38.         return '<Instance of %s, address %s:\n%s' % (
  39.             self.__class__.__name__,
  40.             id(self),
  41.             self.__attrnames())
  42.  
  43.     def __attrnames(self):
  44.         result = ''
  45.         for attr in dir(self):
  46.             if attr[:2] == '__' and attr[-2:] == '__':
  47.                 result += '\tname %s=<>\n' % attr
  48.             else:
  49.                 result += '\tname %s=%s\n' % (attr, getattr(self, attr))
  50.         return result
  51.  
  52.  
  53. class ListTree:
  54.     """
  55.     Примесный класс, в котором метод __str__ просматривает все дерево классов
  56.     и составляет список атрибутов всех объектов, находящихся в дереве выше
  57.     self;
  58.     """
  59.     def __str__(self):
  60.         self.__visited = {}
  61.         return '<Instance of {0}, address {1}:\n{2}{3}'.format(
  62.                     self.__class__.__name__,
  63.                     id(self),
  64.                     self.__attrnames(self, 0),
  65.                     self.__listclass(self.__class__, 4))
  66.  
  67.     def __listclass(self, aClass, indent):
  68.         dots = '.' * indent
  69.         if aClass in self.__visited:
  70.             return '\n{0}<Class {1}:, address {2}: (see above)>\n'.format(dots, aClass.__name__, id(aClass))
  71.         else:
  72.             self.__visited[aClass] = True
  73.             genabove = (self.__listclass(c, indent+4)
  74.                     for c in aClass.__bases__)
  75.             return '\n{0}<Class {1}, address {2}:\n{3}{4}{5}>\n'.format(dots, aClass.__name__, id(aClass), self.__attrnames(aClass, indent),''.join(genabove), dots)
  76.  
  77.     def __attrnames(self, obj, indent):
  78.         spaces = ' ' * (indent+4)
  79.         result = ''
  80.         for attr in sorted(obj.__dict__):
  81.             if attr.startswith('__') and attr.endswith('__'):
  82.                 result += spaces + '{0}=<>\n'.format(attr)
  83.             else:
  84.                 result += spaces + '{0}={1}\n'.format(attr, getattr(obj, attr))
  85.         return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement