5
votes

So is it possible to get a dictionary/list of the attributes ONLY for the most specific class ? So far I'm using

   for attr, value in obj.__class__.__dict__.iteritems():

But this will also give me the attibutes defined in superclasses. Is there any way to avoid this?

3
This question needs repair. It gives the erroneous impression obj.__class__.__dict__ includes superclass attributes. - Bob Stein
Similar thing happens for me. I use obj.__class__.__dict__.iteritems(). On my local - python 2.7, Widows OS it gives me attributes defined for given class w/o considering superclasses. However, in dev env with the same python 2.7 (same venv), Linux OS it gives me all superclass attributes as well. - ruvinbsu

3 Answers

5
votes

Extract from the python documentation

A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although for new-style classes in particular there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes

In other words, __dict__ contains only "local" attributes of the class, the superclass's attributes are stored in the superclass __dict__.

So, you can use __class__.__dict__.iteritems() to retrieve only the class attributes.

On Python 3 you should use __class__.__dict__.items().

3
votes

If you want to get a dict of all class attributes and their values, including inherited classes, then you might want to use the following code:

cls_dict = { attr: getattr(obj.__class__, attr) 
             for attr in dir(obj.__class__) }
for attr, val in cls_dict.iteritems():
    logging.info("%s = %s", attr, val)
2
votes

It does not show me superclass's attributes:

>>> class A(object):
    def a(self):
        print a
    b = 3

>>> a = A()
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
>>> list(a.__class__.__dict__)
['a', '__module__', 'b', '__dict__', '__weakref__', '__doc__']

__module__, __dict__, __weakref__, __doc__ seem to be attributes created for each class by default.

This list of default attributes differs for old style classes:

>>> class B:
    pass

>>> list(B().__class__.__dict__)
['__module__', '__doc__']