Why a class when there will only be one instance?

Michael Chermside mcherm at mcherm.com
Wed May 26 09:30:57 EDT 2004


Mitchell Timin writes:
> I see the value of a class when two or more instances will be created,
> but Python programmers regularly use a class when there will only be one
> instance.
> What is the benefit of this?

Some people have learned to think in terms of objects, so they find it
useful, mentally, if everything is an object. (Particularly true, in my
experience, of people coming from a Java background.)

Mitchell adds later:
> OK, that makes some sense - to associate certain data and code items and
> separate them from other code and data.  Wouldn't that purpose be served
> even better by putting them into a different file, and not bother with a
> class?

Other people are comfortable with a procedural paradigm and will use
modules for this purpose. That's OK... there are numerous examples in the
Python libraries.

Roy Smith commented:
> More than that, most times I've decided to not bother making something a
> class because it was too simple, I've eventually added enough
> functionality to it to change my mind and have to re-do things.

And finally, some people are comfortable with both paradigms, but
prefer to use objects most of the time. The overhead of typing "self"
is remarkably small (if you're a slow typist, define a macro!), and
they find the objects to be more flexible later.

Either way works. But the two most common reasons I've seen for
Python users to be "object happy" are because they don't know any
better, and because they DO know better.

-- Michael Chermside





More information about the Python-list mailing list