Singleton class: what is the purpose?

Gerrit Holl gerrit at nl.linux.org
Thu Jun 5 13:15:36 CEST 2003


Hi,

Guido's article on unifying types and classes mentions singleton classes.
It says:

"""
As another example of __new__, here's a
way to implement the singleton pattern.
"""
(http://www.python.org/2.2.3/descrintro.html)

What is a singleton class? What is the purpose of a singleton class?

On the web, I have found that a singleton class allows only one instance.
Is that correct? If so, it should be easily implementable with:

 20 >>> class Singleton(object):
 20 ...  instances = []
 20 ...  def __init__(self):
 20 ...   if len(self.__class__.instances) == 0:
 20 ...    self.__class__.instances.append(self)
 20 ...   else:
 20 ...    raise Exception("No way jose!")
 20 ... # to do it correct, I think getrefcount would me neccesary
 53 >>> Singleton()
<__main__.Singleton object at 0x403afe4c>
 54 >>> Singleton()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 7, in __init__
Exception: No way jose!
 55 >>> del Singleton.instances[0] # delete the last reference to the object
 56 >>> Singleton()
<__main__.Singleton object at 0x403affac>

But what is the purpose of a Singleton class?

yours,
Gerrit.

-- 
203. If a free-born man strike the body of another free-born man or
equal rank, he shall pay one gold mina.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list