[Tutor] The python implementation of the "class relationship".

Alan Gauld alan.gauld at btinternet.com
Fri Nov 11 01:49:44 CET 2011


On 10/11/11 09:23, Jerry Zhang wrote:
> As you know, there are several kinds of relationships between classes in
> the UML -- dependency, association, aggregation, composition.

There are several more besides, but lets not get carried away... :-)

> Q1. Is there any article or code example on its implementation in python?

Probably if you try using google, but the principles are simple.

Dependencies are both loose and implicit in Python.
If an object uses another object in its implementation there is a 
dependency relationship, but the dependency is only on the operations 
exposed by the object not necessarily on the object, or even on
its type.

Association is likewise loose. If an attribute refers to another object 
then there is an association. If the referenced object is part of a 
collection then it is a 1-M association.

Aggregation is a form of association and nothing more.

Composition is a form of aggregation/association.

Because of the way Python variables work object attributes can only ever 
be references to other objects, they objects are never tightly bound 
together.

The relationships implied by UML are relationships of logical intent. In 
Python it's up to you to "enforce" the intent by the way you write your 
code. UML provides a wide variety of modeling concepts which the modeler 
can use depending on the concept he wishes to convey and also based on 
the implementation language. If designing for a language like C++ or 
Java it may make sense to specify precisely which relationship to use. 
In a freer language, like Python, you may just model everything as 
associations and/or aggregation. UML does not require anything more 
specific any more than it requires that you include deployment designs 
or state machines. They are tools in the toolbox, that's all. If you are 
sculpting in plasticine you probably don't need your power chisel, if 
you are using granite it might be useful. Pick the tool for the job.

> Q2. More specific, in composition model, the container object may be
> responsible for the handling of embedded objects' lifecycle. The common
> way would be adding __del__ to the container class or something else?

That would be one way, and of course by having an __init__ method too.
You might even go one step further and use a __new__ so that the 
relationship is already extant by the time the program hits __init__

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list