class static variables and __dict__

Zack goldsz at gmail.com
Sun Feb 17 01:44:34 CET 2008


Dustan wrote:
> On Feb 16, 5: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
> 
> I know you're probably dumping this for dir(), but I should still warn
> you: This function modifies the class dictionary, which might not have
> been what you intended.

I'm not actually do anything with this, or dir, just messing around 
learning python (I would use dir instead of this if I had a need 
though). I had completely missed that I wasn't copying the dicts. Thanks 
for that catch.

-- 
Zack



More information about the Python-list mailing list