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?
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()
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With