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

Container Properties

Program gif defines the methods getCount, getIsEmpty and getIsFull. The getCount method simply returns the number of objects in the container.

   program4540
Program: Container methods and properties.

The getIsEmpty and getIsFull methods are bool-valued methods which indicate whether a given container is empty or full, respectively. Notice that the getIsEmpty get accessor does not directly access the count instance attribute. Instead it uses Count property. As long as the Count property has the correct semantics, the IsEmpty property will too.

In some cases, a container is implemented in a way which makes its capacity finite. When this is the case, it is necessary to be able to determine when the container is full. IsFull is a bool-valued property that provides a get accessor that returns the value True if the container is full. The default version always returns False.

Program gif also defines the properties count, isEmpty and isFull. Properties are Python object attributes that are referenced like instance attributes, but which are implemented using methods. For example, a reference to the count property results in a call to the getCount method. Similarly. a reference to the isEmpty property results in a call to the getIsEmpty method, and a reference to the isFull property results in a call to the getIsFull method.

Notice that the properties are implemented as lambda expressions. The reason for this is that when a Python property is created it is bound to a specific method instance. The problem with this is that if a property is bound to a specific method instance in a base class, and a derived method overrides the method, the property still remains bound to the original base class method. Thus, we would have to also override the property in the derived class in order to get the desired behavior. By binding the property to a lambda function that calls the desired method, when the method is overridden in a derived class, the property need not also be overridden in that derived class.


next up previous index

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