Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

__iter__ Method

Program gif defines the __iter__ method of the StackAsLinkedList class. The __iter__ method returns an instance of the nested class StackAsLinkedlist.Iterator that implements the iterator protocol (lines 3-16).

   program5513
Program: StackAsLinkedList class __iter__ method.

The Iterator class has two instance attributes, _container and _position. The _container instance attribute refers to the stack whose elements are being enumerated. The _position instance attribute is used to keep track of the position in the linked list of the next object to be enumerated.

The purpose of the _next method is to advance the iterator to the next object in the stack and to raise a StopIteration exception when there are no more elements to be enumerated. In Program gif elements remain as long as the _position is not None. Clearly, the running time of _next is O(1).


next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.