开发者

python get only class attribute no superclasses

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 开发者_StackOverflow中文版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)


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__']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜