[Tutor] Walking up
Magnus Lycka
magnus@thinkware.se
Tue Nov 26 12:18:11 2002
At 06:34 2002-11-26 -0600, Don Arnold wrote:
>I'm no OO expert, but here's my two cents. Have your Child store a reference
>to its Parent in its constructor:
Maybe you are? :)
That is the normal way of doing this, and you certainly see a
lot of that in GUI code. Often, the GUI widgets have standard
functions to access parent objects.
On the other hand, you might want to be a bit careful with this.
E.g. if a child object can have several parent objects, it might
be a bit tricky to handle.
In general, an object should be able to handle it's own attributes
(whether they are simple values or full instance objects) as well
as parameters passed to its methods, and objects it creates in its
own local scopes.
An object is probably more generically useful if it knows and
assumes as little as possible about it's surroundings. If a child
object never tries to get any attribute from a parent object, it
might be useful regardless of the class of it's parent object. It
might not even have a parent object. If it stores a parameter it
gets in its __init__ as self.parent and does "str(self.parent)"
somewhere in it's code, it will always work (whether it works in
a meaningful way is another issue). If it does
"self.parent.parent_text" it will cause an AttributeError it it's
parent doesn't have an attribute called "parent_text".
It's a good thing if a class not only works in its originally
planned context, but both in testing and debugging, *and* in code
that needs the features that the class provides, but otherwise
look different than the code it was written to be part of.
It's usually a good idea to have a loose coupling between classes.
This means that they should know as little as possible about each
other. But of course, we have to compromise all the time. Just try
to make sure that you don't inadvertantly make it harder to chage
the code in the future than it has to be. But these are things we
need to learn by experience I guess.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se