Iterating over a custom object in python
Oct 22nd, 2008 by jbloom
A coworker recently needed to iterate over a custom object in python. It’s pretty easy to do, you just need to implement the __iter__ method on your object.
Here’s some example code that shows you how to extend your object, returning everything in your objects local dictionary:
class IterableObject(object): def __iter__(self): for item in self.__dict__: yield self.__dict__[item]
Now for sample usage:
myObj = IterableObject() myObj.name = "Johnny Hammersticks" myObj.otherProperty = "Something Else" myObj.testList = [1,2,3,4] myObj.testDict = {1:'one', 2:'two'} # Serialize the IterableObject into json for x in myObj: print x, type(x)
which returns:
Something Else <type 'str'> {1: 'one', 2: 'two'} <type 'dict'> [1, 2, 3, 4] <type 'list'> Johnny Hammersticks <type 'str'>
Oh and another handy feature of this dictionary style approach, you can do easy string formatting/printing of the object properties in this style.
print "Hi %(name)s, your list %(testList)s" % myObj.__dict__
Which prints:
Hi Johnny Hammersticks, your list: [1, 2, 3, 4]