Simple Iterable Objects in Python
Sometimes the python documentation can give too many details such that its difficult to get answers to simple questions. One that I’ve just worked through is “iterable objects.” For example, if you have an object called Family and you want to display a list of all the members of that family, you might use this code:
family = Family('Nuzums')
for person in family:
print person['first_name']
Shouldn’t be hard, right? Its not, once you figure it out. You start out with your usual class definition, then you need to add the following methods:
next(self): returns the next item from the list__getitem__(self, item): returns a specific item from the list__iter__(self): returnsselfassuming you’ve added the above two methods
Here’s an example:
class Family:
def __init__(self, last_name):
if last_name == 'Nuzums':
self.members = (
{'first_name': 'mommy'},
{'first_name': 'daddy'},
{'first_name': 'son'},
{'first_name': 'daughter'},
)
self.count = 0
def next(self):
if self.count >= len(self.members):
self.count = 0
raise StopIteration
else:
c = self.count
self.count = c + 1
return self.members[c]
def __getitem__(self, item):
return self.members[item]
def __iter__(self):
return self
That should do it. Note there’s nothing magical about the use of the word ‘members’ above. As long as next and __getitem__ know what to do, the magic is done. This example is extremely simple. If you have some enhancements to suggest, please post them as a comment.
Bearfruit
Comments
iterating multiple families
Thanks for the sympathy on the Python documentation, particularly http://docs.python.org/lib/typeiter.html - it’s a bit of a circular explanation.
Your example shows a good way to list all attributes of a single instance, but how about listing all instances of an object?
How would you modify this example to list all of the instances (the families), such as “Nuzum, Jones, Smith, [etc.]”?
Thanks!
Matt (b)
I don't know
That’s a good question, I don’t know the answer. I know that modules get their own namespace so maybe the module can have a singleton that keeps track of instances. This could cause thread safety issues so there’s probably a better way.
Post new comment