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

The Container Class __str__ Method

One of the methods defined in the Python object class is the __str__ method. Consequently, every Python object supports the __str__ method. The __str__ method is required to return a string that represents the object ``textually.'' It is typically invoked in situations where it is necessary to print out a human-readable representation of an object.

Program gif defines the __str__ method of the abstract Container class. This method is provided to simplify the implementation of classes derived from the Container class. The default behavior is to print out the name of the class and then to print each of the elements in the container, by using the accept method together with a visitor.

   program4725
Program: Container class __str__ method.

The StrVisitor is a visitor. It uses uses its _string instance attribute to accumulate the textual representations of the objects it visits. (It also makes sure to put in commas as required).

The final result returned by the Container class __str__ method consists of the name of the container class, followed by a comma-separated list of the contents of that container enclosed in braces { and }.


next up previous index

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