Is it possible to create a python iterator over pre-defined mutable data?
Posted
by Wilduck
on Stack Overflow
See other posts from Stack Overflow
or by Wilduck
Published on 2010-05-30T22:05:26Z
Indexed on
2010/05/30
22:12 UTC
Read the original article
Hit count: 257
I might be doing this wrong, if I am, let me know, but I'm curious if the following is possible:
I have a class that holds a number of dictionaries, each of which pairs names to a different set of objects of a given class. For example:
items = {"ball" : ItemInstance1, "sword" : ItemInstance2}
people = {"Jerry" : PersonInstance1, "Bob" : PersonInstance2, "Jill" : PersonInstance3}
My class would then hold the current items and people that are availible, and these would be subject to change as the state changes:
Class State:
def __init__(self, items, people):
self.items = items
self.people = people
I would like to define a iter() and next() method such that it iterates through all of the values in its attributes. My first question is whether or not this is possible. If it is, will it be able to support a situation as follows:
I define items and people as above then:
state = State(items, people)
for names, thing in state:
print name + " is " + thing.color
items[cheese] = ItemInstance3
for names, thing in state:
print name + " weighs " + thing.weight
While I feel like this would be usefull in the code I have, I don't know if it's either possible or the right approach. Everything I've read about user defined iterators has suggested that each instance of them is one use only.
© Stack Overflow or respective owner