Modules vs Classes

Alex Martelli aleax at aleax.it
Fri May 10 04:14:41 EDT 2002


jb wrote:

> I use PyQt and need classes very much. I just wonder, if it is not a good
> idea to have one (complicated) class in an own module and storing private
> members of this class as global variables in the module.
> By doing so, the variables cannot be easily accessed from outside (of
> course you can import them) and I can write simply h0 for the height of an
> object instead of writing self.h0.
> 
> Is this good programming tyle?

Generally, no, but it depends.  If you ever need more than one instance
of the class, then it's obviously a disaster if what should be per-instance
state is elsewhere, e.g. in module-globals, so instances HAVE to share it
rather than each getting its own.  But if what you're looking for is how
to design a class of which only one instance will EVER exist, then, yes,
a module is one possibility.  The minor conveniences you hypothesize are
not going to materialize -- import is *needed* for any other code to use
that class, so of course all of the toplevel variables of the module
will be routinely accessible, and the tiny convenience of writing 'h0'
rather than 'self.h0' is overwhelmed by the need to add a 'global h0'
into every function or method that may ever rebind name 'h0'.

So the real issue is just -- how many instances of this class will ever
be allowed to exist?  If *ONE* is the "obvious" answer, do consider a
module instead.  Otherwise, use a real class, of course.


Alex




More information about the Python-list mailing list