[Tutor] implementing relationship between objects
Tue Apr 1 07:23:01 2003
> How would you implement in python a 'relational' 1:1, 1:N, N:N
> relationship between objects?
A simple reference in each object. Since Python varable names are references
there is no need for anything else.
One object holds a list(or dictionary) of references. Potentially each
the list holds a reference to the "parent" - this is what the widgets in the
containment tree do.
Usually best modelled by an explicit mapping object, either a dictionary of
or a pair of dictionaries for two way lookup. Perhaps wrapping it in a class
appropriate methods to maintain consistency. This is by far the hardest of
> Of course both 'sides' should know about the other and changing one
> 'side' of the relation should affect the other side (kind of referetial
The manipulation would normally be done by the methods of the objects.
It depends on exactly how much coupling you need/want.
Change A to refer to C, implies what? That B be set to None? (what if there
a contraint that B always points to something - do we delete B or return
And as part of setting C as the new reference from A we need to set C to
So we wind up with:
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
you are trying to solve, in which case expect a lot of pain - generic
are invariably difficult!)