How to build Hierarchies of dict's? (Prototypes in Python?)

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Feb 23 18:43:43 EST 2007


En Fri, 23 Feb 2007 17:53:59 -0300, Charles D Hixson  
<charleshixsn at earthlink.net> escribió:

> I'm sure I've read before about how to construct prototypes in Python,
> but I haven't been able to track it down (or figure it out).
>
> What I basically want is a kind of class that has both class and
> instance level dict variables, such that descendant classes
> automatically create their own class and instance level dict variables.
> The idea is that if a member of this hierarchy looks up something in
> it's local dict, and doesn't find it, it then looks in the class dict,
> and if not there it looks in its ancestral dict's.  This is rather like
> what Python does at compile time, but I want to do it at run time.

Well, the only thing on this regard that Python does at compile time, is  
to determine whether a variable is local or not. Actual name lookup is  
done at runtime.
You can use instances and classes as dictionaries they way you describe.  
Use getattr/setattr/hasattr/delattr:

py> class A:
...   x = 0
...   y = 1
...
py> class B(A):
...   y = 2
...
py> a = A()
py> setattr(a, 'y', 3) # same as a.y = 3 but 'y' may be a variable
py> print 'a=',vars(a)
a= {'y': 3}
py>
py> b = B()
py> print 'b=',vars(b)
b= {}
py> setattr(b,'z',1000)
py> print 'b=',vars(b)
b= {'z': 1000}
py> print 'x?', hasattr(b,'x')
x? True
py> print 'w?', hasattr(b,'w')
w? False


-- 
Gabriel Genellina




More information about the Python-list mailing list