for new-style classes, you can loop over entries in the class instance's __dict__:
class Example(object):
def __init__(self):
self.one = 1
self.two = 2
self.three = 3
self.four = 4
def members(self):
all_members = self.__dict__.keys()
return [ (item, self.__dict__[item]) for item in all_members if not item.startswith("_")]
print Example().members()
#[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
Since the __dict__ is just a dictionary you can loop over it to select the items you need (in the above example I'm filtering out items starting with underscores but it could be any criterion you want). You can get the same information with the builtin command vars
:
test = Example()
print vars(test):
# {'four': 4, 'three': 3, 'two': 2, 'one': 1}
and again you can select the keys you need.
You can also use the inspect
module for more detailed inspection of an object:
import inspect
print inspect.getmembers(Example())
#[('__class__', <class '__main__.Example'>), ('__delattr__', <method-wrapper '__delattr__' of Example object at 0x000000000243E358>), ('__dict__', {'four': 4, 'three': 3, 'two': 2, 'one': 1}), ('__doc__', None), ('__format__', <built-in method __format__ of Example object at 0x000000000243E358>), ('__getattribute__', <method-wrapper '__getattribute__' of Example object at 0x000000000243E358>), ('__hash__', <method-wrapper '__hash__' of Example object at 0x000000000243E358>), ('__init__', <bound method Example.__init__ of <__main__.Example object at 0x000000000243E358>>), ('__module__', '__main__'), ('__new__', <built-in method __new__ of type object at 0x000000001E28F910>), ('__reduce__', <built-in method __reduce__ of Example object at 0x000000000243E358>), ('__reduce_ex__', <built-in method __reduce_ex__ of Example object at 0x000000000243E358>), ('__repr__', <method-wrapper '__repr__' of Example object at 0x000000000243E358>), ('__setattr__', <method-wrapper '__setattr__' of Example object at 0x000000000243E358>), ('__sizeof__', <built-in method __sizeof__ of Example object at 0x000000000243E358>), ('__str__', <method-wrapper '__str__' of Example object at 0x000000000243E358>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x0000000002255AC8>), ('__weakref__', None), ('four', 4), ('members', <bound method Example.members of <__main__.Example object at 0x000000000243E358>>), ('one', 1), ('three', 3), ('two', 2)]