How to Loop Through All Properties on a Python Object
At its most basic level, a Python class contains at least one variable that contains some sort of data value. More often than not, objects created from classes contain multiple variable properties that define how they function. In some programs it might become useful to list those properties and their values in order to keep track of an object. In this instance you can derive a class from the object class, and use the built-in __dict__ attribute of the object class to iterate over.
Instructions
-
-
1
Create a basic class, containing three data variables, that inherits functionality from the object base class:
>>>class A(object):
. . . def __init__(self):
. . . self.x = 1
. . . self.y = 2
. . . self.z = 3
>>> -
2
Create an instance of the class:
>>>a = A()
>>>a.x
1
>>>a.y
2
>>>a.z
3 -
-
3
Set up a for loop to iterate over the items in object a. This uses the __dict__ built-in type, which returns a series of key-value pairs:
>>>for attr, value in a.__dict__.iteritems():
. . . print attr, value
. . .
x 1
y 2
z 3
-
1