class static variables and __dict__
Arnaud Delobelle
arnodel at googlemail.com
Sun Feb 17 04:28:42 EST 2008
On Feb 16, 11:59 pm, Zack <gol... at gmail.com> wrote:
> Zack wrote:
> > Diez B. Roggisch wrote:
> >> Zack schrieb:
> >>> If I have a class static variable it doesn't show up in the __dict__
> >>> of an instance of that class.
>
> >>> class C:
> >>> n = 4
>
> >>> x = C()
> >>> print C.__dict__
> >>> {'__module__': '__main__', '__doc__': None, 'n': 4}
> >>> print x.__dict__
> >>> {}
>
> >>> This behavior makes sense to me as n is not encapsulated in x's
> >>> namespace but what method can you use on x to find all available
> >>> attributes for that class?
>
> >> x.__class__.__dict__
>
> >> Diez
>
> > This would leave out any attributes of base classes. Not that I asked
> > for that functionality in my original post but is there a way to get all
> > attributes qualified by x. ? I see that I could walk the dict of x,
> > x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is
> > there a built in method for doing this?
>
> I believe this accomplishes what I'm looking for. I'm not positive it is
> correct or if there are cases I've missed. It would be nice if there is
> a simple python builtin for finding the fully qualified dict.
>
> def fullDict(obj):
> '''
> Returns a dict with all attributes qualified by obj.
>
> obj is an instance of a class
>
> '''
> d = obj.__dict__
> # update existing items into new items to preserve inheritance
> tmpD = obj.__class__.__dict__
> tmpD.update(d)
> d = tmpD
> supers = list(obj.__class__.__bases__)
> for c in supers:
> tmpD = c.__dict__
> tmpD.update(d)
> d = tmpD
> supers.extend(c.__bases__)
> return d
>
> --
> Zack
Child class attributes override base class ones, so your function will
get the wrong dict I think in cases like:
class A(object):
x = 1
class B(A):
x = 2
Why not do something like this:
def fulldict(obj):
d = {}
for t in reversed(type(obj).__mro__):
d.update(t.__dict__)
d.update(obj.__dict__)
return d
--
Arnaud
More information about the Python-list
mailing list