Why a class when there will only be one instance?

John Roth newsgroups at jhrothjr.com
Wed May 26 08:12:13 EDT 2004


<SeeBelow at SeeBelow.Nut> wrote in message news:40B3E861.29B033D5 at shaw.ca...
> 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?  It has a disadvantage of a whole lot of
> "self."
> being required everywhere, making the code less readable.  Also, since a
> strength of Python is rapid application development, it slows one down
> to have to put in all those self.'s.  The code seems much cleaner to me
> without classes that have only one instance.  Oh, also, all the methods
> of this class will have to have the instance name prepended to them.

I'm only aware of one domain (interactive fiction) where it is really
common to have single instance classes. That's served by a number
of special purpose languages (Inform, TADS and Hugo spring to
mind). Your example (of single use classes in a UI context) seems
to be a bit contrived. I've usually found that I could get quite a bit
of code reuse out of UI classes simply by thinking the problems
through.

Granted, single use classes aren't uncommon, but instances of
other classes are much more common in most programs. In
Python, there are a number of ways of getting singletons without
very much extra effort.

> I would appreciate it if someone could explain the advantages of doing
> this, or at least the sociological reasons why it occurs.

Both have their uses. The class / instance dicotomy comes from
the earliest days of object oriented programming, and experiments
with classless languages (see the Prothon stuff currently going on,
also the IO language) have never been very compelling. A lot of
people (which include me) think that it's much to easy to get sloppy
with that paradigm.

The other thing to understand is that in most OO languages a
class is a declaration: it does not appear in the actual object
program other than as a framework for the instances that are
created. Python is one of the few languages where classes are
first class objects.

John Roth


> Mitchell Timin





More information about the Python-list mailing list