Skip to content

Commit 99097ed

Browse files
committed
Added listinherited.py
1 parent 37f37f4 commit 99097ed

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
- [timer3.py](timer3.py) Homegrown timing tools for function calls.
2222
- [classtree.py](classtree.py) Climb inheritance tree using namespace links, displaying higher superclasses with indentation for height
2323
- [listinstance.py](listinstance.py) Mix-in class that provides a formatted print() or str()
24+
- [listinherited.py](listinherited.py) Mix-in class that provides a formatted print() or str() (Use dir() to collect both instance attr and names inherited from its classes)
2425

2526
---
2627

listinherited.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#!/usr/bin/env python3
2+
# File listinherited.py (2.x + 3.x)
3+
4+
5+
class ListInherited:
6+
"""
7+
Use dir() to collect both instance attr and names inherited from
8+
its classes; Python 3.x shows more name than 2.x because of the
9+
implied object superclass in the new-style class model; getattr()
10+
fetches inherited names not in self.__dict__; user __str__, not
11+
__repr__, or else the loops when printing bound method!
12+
"""
13+
14+
def __attrname(self):
15+
result = ''
16+
for attr in dir(self): # instance dir
17+
if attr[:2] == '__' and attr[-2:] == '__':
18+
result += '\t%s\n' % attr
19+
else:
20+
result += '\t%s=%s\n' % (attr, getattr(self, attr))
21+
return result
22+
23+
def __str__(self):
24+
return '<Instance of %s, address %s:\n%s>' % (
25+
self.__class__.__name__,
26+
id(self), # My address
27+
self.__attrname()) # name=value list
28+
29+
30+
def tester(listerclass, sept=False):
31+
32+
class Super:
33+
34+
def __init__(self):
35+
self.data1 = 'spam'
36+
37+
def ham(self):
38+
pass
39+
40+
class Sub(Super, listerclass):
41+
42+
def __init__(self):
43+
Super.__init__(self)
44+
self.data2 = 'eggs'
45+
self.data3 = 42
46+
47+
def spam(self):
48+
pass
49+
50+
instance = Sub()
51+
print(instance)
52+
if sept:
53+
print('-' * 80)
54+
55+
56+
if __name__ == '__main__':
57+
58+
tester(ListInherited)

0 commit comments

Comments
 (0)