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

Associations

 

An association is an ordered pair of objects. The first element of the pair is called the key ; the second element is the value  associated with the given key.

Associations are useful for storing information in a database  for later retrieval. For example, a database can be viewed as a container that holds key-and-value pairs. The information associated with a given key is retrieved from the database by searching the database for an the ordered pair in which the key matches the given key.

Program gif introduces the Association class. The Association class concrete extension of the abstract Object class given in Program gif.

   program4810
Program: Association class __init__ method.

As shown in Program gif, we implement an association using a Python tuple . The __init__ method always creates a tuples with exactly two elements. The first element of the tuple represents the key of the association and the second element of the tuple represents the value associated with the given key.

Two properties of an Association are defined in Program gif. The key property returns the value of the first element of the tuple and the value property returns the value of the second element of the tuple.

   program4824
Program: Association properties.

The remaining methods of the Association class are defined in Program gif. The _compareTo method is used to compare associations. Its argument is an object that is assumed to be an instance of the Association class. The _compareTo method is one place where an association distinguishes between the key and the value. In this case, the result of the comparison is based solely on the keys of the two associations--the values have no role in the comparison.

   program4843
Program: Association methods.

Program gif also defines a __str__ method. The purpose of the __str__ method is to return a textual representation of the association. In this case, the implementation is trivial and needs no further explanation.


next up previous index

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