So I’ve done some looking online and throught the documentation, but I’m having troubling finding out how to do this. I am working on creating an adventure game. I have a level class (which contains a bunch of rooms) and a Room class. I would like to be able to do something like the following.
l = Level()
for room in l:
#following code here
This seems pretty simple to me, however I can’t find the correct procedures for implementing a custom iterator. This may be an easy answer, but I’m having trouble finding it online. Any help is greatly appreciated!
Use
__iter__with an iterator-generator. E.g.An iterator-generator is basically a psuedo-method used to implement an iterator. Note that there is no requirement that the generator use a for loop. It can use any combination of constructs (if, for, while, etc.) as needed. Basically, you just have to remember that the caller will get elements in the order you “call” yield, and the iteration will end when the method does.
See this section of the Python tutorial.