reflection – How to enumerate an objects properties in Python?

reflection – How to enumerate an objects properties in Python?

for property, value in vars(theObject).items():
    print(property, :, value)

Be aware that in some rare cases theres a __slots__ property, such classes often have no __dict__.

dir() is the simple way. See here:

Guide To Python Introspection

reflection – How to enumerate an objects properties in Python?

See inspect.getmembers(object[, predicate]).

Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.

>>> [name for name,thing in inspect.getmembers([])]
[__add__, __class__, __contains__, __delattr__, __delitem__, 
__delslice__,    __doc__, __eq__, __format__, __ge__, __getattribute__, 
__getitem__, __getslice__, __gt__, __hash__, __iadd__, __imul__, __init__, __iter__, 
__le__, __len__, __lt__, __mul__, __ne__, __new__, __reduce__,__reduce_ex__, 
__repr__, __reversed__, __rmul__, __setattr__, __setitem__, __setslice__, 
__sizeof__, __str__, __subclasshook__, append, count, extend, index, 
insert, pop, remove, reverse, sort]
>>> 

Leave a Reply

Your email address will not be published. Required fields are marked *