How to build Hierarchies of dict's? (Prototypes in Python?)
Toby
etatoby at gmail.com
Sun Feb 25 07:19:12 EST 2007
Charles D Hixson wrote:
> a class whose sub-classes automatically have unique class variables of
> a determined form such that I can do a hierarchical search through them
Something like this?
(scroll down to see the results)
# --- begin ---
class AttrSearch(object):
@classmethod
def getclassattrset(cls, name):
s = set()
if name in cls.__dict__:
s.add((cls.__name__, cls.__dict__[name]))
for base in cls.__bases__:
try:
s.update(base.getclassattrset(name))
except AttributeError:
pass
return s
def getattrset(self, name):
s = set()
try:
s.add((None, self.__dict__[name]))
except KeyError:
pass
s.update(self.__class__.getclassattrset(name))
return s
def __getattribute__(self, name):
if name.startswith('__'): #XXX not pretty
return object.__getattribute__(self, name)
found = AttrSearch.getattrset(self, name)
print 'Looking for "%s" in a %s instance, found %d candidates:' \
% (name, self.__class__.__name__, len(found))
print '\n'.join([ ' %-4s %s' % x for x in found ])
print '(now choose wisely what to return)'
class A(AttrSearch):
a = 1
class B(A):
a = 2
class C(A):
a = 3
class D(B, C):
a = 4
D().a
# --- end ---
Results:
Looking for "a" in a D instance, found 4 candidates:
A 1
B 2
C 3
D 4
(now choose wisely what to return)
Toby
More information about the Python-list
mailing list