How to build Hierarchies of dict's? (Prototypes in Python?)
Charles D Hixson
charleshixsn at earthlink.net
Sun Feb 25 13:29:24 EST 2007
Toby wrote:
> 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
>
Yes, thank you.
(I'd come up with a kludge, but this is much nicer.)
More information about the Python-list
mailing list