Why a class when there will only be one instance?

François Pinard pinard at iro.umontreal.ca
Thu May 27 17:56:37 EDT 2004


[SeeBelow at SeeBelow.Nut]

> 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?

There are two advantages for me:

1) It helps at keeping related data and actions together within a named
concept.  This further increases legibility and eases maintenance.

2) The global namespace stays much cleaner.  (A side effect is that I
never need the `global' declaration in practice.)

> It has a disadvantage of a whole lot of "self." being required
> everywhere, making the code less readable.

While those `self.' are a bit of a clutter indeed, they help me to read
that this routine is calling this other one within the same conceptual
part of the whole program, and as such, they had documentation value.

> Oh, also, all the methods of this class will have to have the instance
> name prepended to them.

It would be `self.' within the class itself, and the instance name
within foreign classes.  This habit stresses the relations between the
parts of the program and eases a better understanding of the whole.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list