[Tutor] Class in a class

Kent Johnson kent37 at tds.net
Fri Feb 18 00:14:01 CET 2005


Luis N wrote:
> Does it make sense to do this:
> 
> In [2]: class AB:
>    ...:     pass
>    ...:
> In [3]: a = AB()
> 
> In [4]: a
> Out[4]: <__main__.AB instance at 0x8428bec>
> 
> In [5]: class BC:
>    ...:     def __init__(self, foo):
>    ...:         self.foo = foo
> 
> In [6]: b = BC(a)
> 
> In [7]: b.foo
> Out[7]: <__main__.AB instance at 0x8428bec>

Absolutely. This is called composition - one object is made up of others. It's a very powerful way 
to create higher-level abstractions from component parts.

For example, I have a project that uses a database. The lowest level of access to the database is 
through a JDBC connection object. I have a generic DbAccess class that builds on the connection to 
provide easier ways to do queries and updates. I have a CbDao class that builds on a DbAccess to 
provide application-specific primitives such as saveCourse() and findCourse(). Higher-level classes 
use a CbDao to do some real work. GUI classes present the results to the user and allow the data to 
be manipulated. So the layering is

GUI - user interaction
Application functionality
CbDao - application-specific database access
DbAccess - generic database access, easy to use
JDBC connection - raw database access, not so easy to use

Kent



More information about the Tutor mailing list