Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python get only class attribute no superclasses

Tags:

python

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?

like image 408
Bogdan Avatar asked Aug 30 '11 10:08

Bogdan


2 Answers

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().

like image 63
Cédric Julien Avatar answered Oct 04 '22 17:10

Cédric Julien


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)
like image 35
Alek Kowalczyk Avatar answered Oct 04 '22 16:10

Alek Kowalczyk