2

Let's say I have this class:

class SomeClass()
    var1
    var2
    var3
.
.
.

Is there a way to loop through all of these instance variables without calling each variable by its name (like if it was an array)?

Wyetro
  • 8,439
  • 9
  • 46
  • 64
Max Segal
  • 1,955
  • 1
  • 24
  • 53

4 Answers4

2

Have a look at 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']
>>> 
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
1

Yes there is a way to do this. From looping over all member variables of a class in python:

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False


members = [attr for attr in dir(Example()) if not callable(attr) and not attr.startswith("__")]
print members

Will give you:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']
Community
  • 1
  • 1
Wyetro
  • 8,439
  • 9
  • 46
  • 64
1

Yes, you can do it like this:

someobj = SomeClass()
for _attr in someobj.__dict__:
    # double underscore are mostly used by python
    if not _attr.startswith("__") and not callable(_attr):
        print someobj.__dict__[_attr]
NeoWang
  • 17,361
  • 24
  • 78
  • 126
1

You can use the inspect standard library module for that.

see Getting attributes of a class

Community
  • 1
  • 1
Josh J
  • 6,813
  • 3
  • 25
  • 47