What is a class?

Paul McGuire ptmcg at austin.rr.com
Wed Mar 5 17:14:23 EST 2008


On Mar 5, 3:49 pm, castiro... at gmail.com wrote:
>
> Classes and modules are really similar.  In Python they're really
> *really* similar.
>
> Actually, at this point, that observation may have more of a
> subjective component than I'm used to asserting.  I pause here for
> corroboration and others' perspectives.  Aren't they?

If all you use classes for is for the purpose of a namespace, and all
of the methods in the class are just staticmethods, then you have used
a class to replicate a module, and they aren't just really, *really*
similar, they are the pretty much the same (at least BEHAVIORALLY
speaking).

But you can't do this:

import Zmodule
zobject = Zmodule()

If you are really using the OO model, and creating instances of
classes, then you *have* to use a class, a module wont cut it.  I'd
say, the less you use a class as an instance factory, the more similar
that class is to a module.

And you can't do this:

class Zclass:

import Zclass

If Zclass is not defined in your local script, you *have* to know what
module it is in, as in:

from zpackage.zmodule import Zclass

I have seen modules compared to classes that implement a Singleton
pattern.  In this case, a class is being used in an intentionally
degenerate way, such that it creates only one instance.  When doing
this in Python, one has the choice of replicating the standard pattern
with a class, or more simply, just using a module.  (Python's language/
object model also permits another option, usually referred to as the
Borg implementation, in which many Python names bind to many Python
instances, but all share the same underlying object state.  But this
is tangential to your question.)

In general I would say the similarity is a behavioral one, an artifact
of the language implementation.  Modules are for code packaging and
namespace definition, classes are for type definition and object
modeling.

For more discussions about how similar classes are to modules, you
might google for "Python singleton".

-- Paul



More information about the Python-list mailing list