Section 13.9. Composition


13.9. Composition

Once a class is defined, the goal is to use it as a model programmatically, embedding this object throughout your code, intermixing use with other data types and the logical flow of execution. There are two ways of utilizing classes in your code. The first is composition. This is where different classes are mingled with and into other classes for added functionality and code reusability. You may create instances of your class inside a larger class, containing other attributes and methods enhancing the use of the original class object. The other way is with derivation, discussed in the next section.

For example, let us imagine an enhanced design of the address book class we created at the beginning of the chapter. If, during the course of our design, we created separate classes for names, addresses, etc., we would want to integrate that work into our AddrBookEntry class, rather than have to redesign each of those supporting classes. We have the added advantages of time and effort saved, as well as more consistent codewhen bugs are fixed in that same piece of code, that change is reflected in all the applications that reuse that code.

Such a class would perhaps contain a Name instance, not to mention others like StreetAddress, Phone (home, work, telefacsimile, pager, mobile, etc.), Email (home, work, etc.), and possibly a few Date instances (birthday, wedding, anniversary, etc.). Here is a simple example with some of the classes mentioned above:

class NewAddrBookEntry(object):   # class definition     'new address book entry class'     def __init__(self, nm, ph):   # define constructor         self.name = Name(nm)      # create Name instance         self.phone = Phone(ph)    # create Phone instance         print 'Created instance for:', self.name


The NewAddrBookEntry class is a composition of itself and other classes. This defines a "has-a" relationship between a class and other classes it is composed of. For example, our NewAddrBookEntry class "has a" Name class instance and a Phone instance, too.

Creating composite objects enables such additional functionality and makes sense because the classes have nothing in common. Each class manages its own namespace and behavior. When there are more intimate relationships between objects, the concept of derivation may make more sense in your application, especially if you require like objects, with slightly different functionality.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net