What do you call a class not intended to be instantiated

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 27 02:45:16 EDT 2008


On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote:

> In article <pan.2008.09.26.07.27.41 at REMOVE.THIS.cybersource.com.au>,
> Steven D'Aprano  <steven at REMOVE.THIS.cybersource.com.au> wrote:
>>On Thu, 25 Sep 2008 21:17:14 -0700, Aahz wrote:
>>>
>>> Seems to me that if all the module is used for is to store state,
>>> you're wasting a file on disk.  I personally prefer to use a class
>>> singleton.
>>
>>I don't recognise the term "class singleton". Can you explain please?
>>How is it different from an ordinary singleton?
> 
> An ordinary singleton is instantiating the class multiple times yet
> returning the same instance object; a class singleton is simply using
> the class directly (like a module).

Amazing. That's *exactly* what I was thinking of when I first asked my 
question.

Since I now no longer think I need such a beast, this is just academic 
curiosity, but given a class singleton, I'd like to be able to call it as 
if it were a function. Normally calling a class object returns an 
instance -- I wish to return something else. Is that just a matter of 
overriding __new__?

This seems to works:

>>> class ClassSingleton(object):
...     thing = (0, 1, 2)
...     def __new__(cls, *args):
...             return len(args+cls.thing)
...
>>> ClassSingleton(1, 2, 4, 8, 16)
8



Is it really that easy?



-- 
Steven



More information about the Python-list mailing list