Why a class when there will only be one instance?

Dave Harris dpharris76 at msn.com
Tue May 25 23:09:36 EDT 2004


Mitchell Timin wrote:
> 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 would appreciate it if someone could explain the advantages of doing
> this, or at least the sociological reasons why it occurs.

I may very well be the person prompting this question -- Mitchell has been 
reviewing some Python code I wrote. As a matter of fact, I asked myself the 
same question, wondering if I was slavishly using a technique that 
obfuscates the code.

In particular (and this may remind list readers of an embarrassing recent 
post by me), I have a window with multiple Frames. Two of the frames, 
CourseView(Tk.Frame) and DetailView(Tk.Frame) contain independent Canvas 
objects. The views have different origins and I found it very convenient to 
set up instance variables named xoffset and yyoffset for coordinate 
translations. The names are meaningful (to me) and serve the same purpose in 
each Canvas. This seems minor, but the idea extends to other orthogonal 
relationships.

The most likely non-class alternative leads to longer function names which 
slow down comprehension and inflate the namespace. For example, instead of:

courseView = CourseView(frame)
courseView.pack()
detailView = DetailView(frame)
courseView.pack()
courseView.drawAll()
detailView.drawAll()

I might have to resort to:

courseView = Frame(frame)
courseView.pack()
courseView.canvas = Canvas(courseView)
courseView.canvas.pack()
detailView = Frame(frame)
detailView.pack()
detailView.canvas = Canvas(detailView)
detailView.canvas.pack()
drawAllCourseView(courseView)
drawAllDetailView(detailView)

(I'm almost positive I made this look as bad as I possibly could. Another 
embarrassment?)

What I decided I like about the class arrangement is the data hiding that 
makes the application conceptually simpler. I cannot (at the moment) 
envision re-use, but I've been wrong about that in my C career more times 
than I can count.

Sorry about the length,
Dave Harris 




More information about the Python-list mailing list