|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# File listtree.py (2.x + 3.x) |
| 3 | + |
| 4 | + |
| 5 | +class ListTree: |
| 6 | + """ |
| 7 | + Mix-in that returns an __str__ trace of the entire class and all |
| 8 | + its object's attrs at and above self; run by print(), str() returns |
| 9 | + constructed string; uses __X attr names to avoid impacting clients; |
| 10 | + recurses to superclasses explicitly, uses str.format() for clarity. |
| 11 | + """ |
| 12 | + |
| 13 | + def __attrnames(self, obj, indent): |
| 14 | + spaces = ' ' * (indent + 1) |
| 15 | + result = '' |
| 16 | + for attr in sorted(obj.__dict__): |
| 17 | + if attr.startswith('__') and attr.endswith('__'): |
| 18 | + result += spaces + '{0}\n'.format(attr) |
| 19 | + else: |
| 20 | + result += spaces + '{0}={1}\n'.format(attr, getattr(obj, attr)) |
| 21 | + return result |
| 22 | + |
| 23 | + def __listclass(self, aClass, indent): |
| 24 | + dots = '.' * indent |
| 25 | + if aClass in self.__visited: |
| 26 | + return '\n{0}<Class {1}:, address {2}: (see above)>\n'.format( |
| 27 | + dots, |
| 28 | + aClass.__name__, |
| 29 | + id(aClass)) |
| 30 | + else: |
| 31 | + self.__visited[aClass] = True |
| 32 | + here = self.__attrnames(aClass, indent) |
| 33 | + above = '' |
| 34 | + for super in aClass.__bases__: |
| 35 | + above += self.__listclass(super, indent + 4) |
| 36 | + return '\n{0}<Class {1}:, address {2}:\n{3}{4}{5}'.format( |
| 37 | + dots, |
| 38 | + aClass.__name__, |
| 39 | + id(aClass), |
| 40 | + here, above, |
| 41 | + dots) |
| 42 | + |
| 43 | + def __str__(self): |
| 44 | + self.__visited = {} |
| 45 | + here = self.__attrnames(self, 0) |
| 46 | + above = self.__listclass(self.__class__, 4) |
| 47 | + return '<Instance of {0}, address {1}:\n{2}{3}>'.format( |
| 48 | + self.__class__.__name__, |
| 49 | + id(self), |
| 50 | + here, above) |
| 51 | + |
| 52 | + |
| 53 | +def tester(listerclass, sept=False): |
| 54 | + |
| 55 | + class Super: |
| 56 | + |
| 57 | + def __init__(self): |
| 58 | + self.data1 = 'spam' |
| 59 | + |
| 60 | + def ham(self): |
| 61 | + pass |
| 62 | + |
| 63 | + class Sub(Super, listerclass): |
| 64 | + |
| 65 | + def __init__(self): |
| 66 | + Super.__init__(self) |
| 67 | + self.data2 = 'eggs' |
| 68 | + self.data3 = 42 |
| 69 | + |
| 70 | + def spam(self): |
| 71 | + pass |
| 72 | + |
| 73 | + instance = Sub() |
| 74 | + print(instance) |
| 75 | + if sept: |
| 76 | + print('-' * 80) |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == '__main__': |
| 80 | + |
| 81 | + tester(ListTree) |
0 commit comments