[Tutor] implementing relationship between objects
alan.gauld@bt.com
alan.gauld@bt.com
Tue Apr 1 07:23:01 2003
> How would you implement in python a 'relational' 1:1, 1:N, N:N
> relationship between objects?
1:1
A simple reference in each object. Since Python varable names are references
there is no need for anything else.
1:N
One object holds a list(or dictionary) of references. Potentially each
object in
the list holds a reference to the "parent" - this is what the widgets in the
Tkinter
containment tree do.
N:N
Usually best modelled by an explicit mapping object, either a dictionary of
lists
or a pair of dictionaries for two way lookup. Perhaps wrapping it in a class
with
appropriate methods to maintain consistency. This is by far the hardest of
the
scenarios.
> Of course both 'sides' should know about the other and changing one
> 'side' of the relation should affect the other side (kind of referetial
> integrity).
The manipulation would normally be done by the methods of the objects.
It depends on exactly how much coupling you need/want.
eg.
A<->B
Change A to refer to C, implies what? That B be set to None? (what if there
is
a contraint that B always points to something - do we delete B or return
failure?)
And as part of setting C as the new reference from A we need to set C to
refer
to A.
So we wind up with:
A->C
C->A
B->None (or is deleted?)
These are application level decisions. The choices will be reflected in the
implementation of the methods. Python is not a relational database and if
thats the behaviour you need you would be best using an RDBMS IMHO.
The usual rules of OO Design apply - work out what you want the objects
to do and implement that. Do not build some generic function and then
bend the problem to suit. (Unless of course the generic solution is the
problem
you are trying to solve, in which case expect a lot of pain - generic
solutions
are invariably difficult!)
Alan G.