views:

36

answers:

1

There is a hierchy of classes. Each class may define a class variable (to be specific, it's a dictionary), all of which have the same variable name. I'd like the very root class to be able to somehow access all of these variables (i.e. all the dictionaries joined together), given an instance of a child class. I can't seem to find the way to do so. No matter what I try, I always get stuck on the fact that I cannot retrieve the direct parent class given the child class. How can this be accomplished?

+1  A: 

As long as you're using new-style classes (i.e., object or some other built-in type is the "deepest ancestor"), __mro__ is what you're looking for. For example, given:

>>> class Root(object):
...   d = {'za': 23}
... 
>>> class Trunk(Root):
...   d = {'ki': 45}
... 
>>> class Branch(Root):
...   d = {'fu': 67}
... 
>>> class Leaf(Trunk, Branch):
...   d = {'po': 89}

now,

>>> def getem(x):
...   d = {}
...   for x in x.__class__.__mro__:
...     d.update(x.__dict__.get('d', ()))
...   return d
... 
>>> x = Leaf()
>>> getem(x)
{'za': 23, 'ki': 45, 'po': 89, 'fu': 67}
Alex Martelli
Perfect! Exactly what I was looking for. Thank you.
MTsoul