[Tutor] communication between class instances

Gonçalo Rodrigues op73418@mail.telepac.pt
Thu Dec 5 07:54:01 2002


From: "Poor Yorick" <gp@pooryorick.com>


> Hi,
>
> I've been studying Python for several months now, and it is my first
> attempt to learn how to program in any language.  I've been trying
> lately to understand some of the nuances of object oriented programming,
> but most of the resources on the web require some knowledge of c++ to
> gist.  So, I'm turning to this list :)  Direct answers or pointers to
> reference material about this question would be greatly appreciated:
>
> Say I have the following classes:
>
>
> class app:
>     def __init(self):
>         self.dbtype = None
>         self.gui=gui(self)
>
> class gui:
>     def __init__(self, app):
>         self.app = app
>         self.main_menu = menu(self.app)

Although this is not incorrect you should be aware that it creates what is
called a cycle: an object A references an object B that references A. In
this case, the usual way that Python (to be correct: CPython) uses to free
memory (reference counting) does not work and the garbage collector has to
kick in to free up these cycles when they are no longer in use. In other
words, if you can avoid cycles do it.

>
> class menu:
>     def __init__(self, app):
>         self.app = app
>
>     def dbtype(self):
>         app.dbtype = 'metakit'
>
>
> So far, instantiating classes and passing references to all other class
> instances that the instance will need to communicate with is the only
> way I've come up with to get class instances to communicate with each
> other.  This seems unwieldy and not really modular.  Is there a better

Why do you say "unwieldy and not really modular"? Passing as arguments to
the __init__ method what the instances need to work properly is a perfect
way of communication.

> way to pass data between class instances?  One thing I really don't like
> is having to pass a reference to the app instance all the way down to
> the menu instance, which really should only be aware of the gui instance
> which instantiates it. Right?
>
> Right?
>
> I'm very confused...
>
> Poor Yorick
> gp@pooryorick.com

With my best regards,
G. Rodrigues