how to get names of attributes

Chris Angelico rosuav at gmail.com
Wed Dec 30 07:34:03 EST 2015


On Wed, Dec 30, 2015 at 11:16 PM, Charles T. Smith
<cts.private.yahoo at gmail.com> wrote:
> I'm glad I discovered __mro__(), but how can I do the same thing for old-
> style classes?

You should be able to track through __bases__ and use vars() at every level:

>>> class X: pass
...
>>> class Y(X): pass
...
>>> class Z(Y): pass
...
>>> X.x=1
>>> Y.y=2
>>> Z.z=3
>>> inst=Z()
>>> inst.i=4
>>> def class_vars(old_style_class):
...     v = {}
...     for cls in old_style_class.__bases__:
...         v.update(class_vars(cls))
...     v.update(vars(old_style_class))
...     return v
...
>>> def all_vars(old_style_inst):
...     v = class_vars(old_style_inst.__class__)
...     v.update(vars(old_style_inst))
...     return v
...
>>> all_vars(inst)
{'i': 4, '__module__': '__main__', 'y': 2, 'x': 1, 'z': 3, '__doc__': None}

I'm not 100% sure I've matched the MRO here, but if all you want is
the complete set of attribute names, this should work - I think.

ChrisA



More information about the Python-list mailing list