[Tutor] Communication between classes
Andrei
project5 at redrival.net
Sun Apr 1 20:46:21 CEST 2007
Hi Greg,
Greg Perry wrote:
> I am still in the process of learning OOP concepts and
> reasons why classes should be used instead of functions etc.
>
> One thing that is not apparent to me is the best way for
> classes to communicate with each other. For example,
Good question. Unfortunately there's no general rule that you can apply
and end up with an undisputably perfect solution.
Classes should communicate on a need-to-know basis. Take for example a
RSS feed reader application. You may have a class representing a feed
and a class representing a post. The feed will know what posts it
contains, but the post probably won't know what feed it comes from. The
interface would display a list of feeds (without knowing their
contents), a list of posts within a feed (this needs to know both feed
and feed contents) and the contents of a single post (knows only about
an individual post).
> I have created an Args class that sets a variety of internal
> variables (__filename, __outputdir etc) by parsing the argv
Be careful with classes that simply act as a container for what are in
fact global variables. A class should do one thing only (of course what
you accept as 'one thing' is open for debate) and encapsulate all that's
necessary for that particular thing. Make sure you're not
overcomplicating your solution by making classes where they're not
really necessary.
> array from th command line. What would be the preferred
> mechanism for returning or passing along those variables
In some cases only some parts of the information contained in class A
are relevant to class B - you should pass only that particular
information, e.g. in the constructor or by setting a property of B. In
your example, if you have a Reader class that is interested in the
filename, you would not pass the whole Args object to it - only the
filename, like this:
myreader = Reader(Args.FileName)
> to another class? Maybe by a function method that returns
> all of those variables?
Use properties if you need getter/setter methods or simple attributes
otherwise. In your case, I would not make __filename etc. 'private'
(that's what the double underscore suggests), then write a getter method
for it - just call it FileName and be done with it. Python idiom here is
more flexible than other languages.
--
Yours,
Andrei
=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
More information about the Tutor
mailing list