[CentralOH] Singleton

Yung-Yu Chen yyc at seety.org
Thu Sep 30 23:54:59 CEST 2010


How about

class singleton(object):
    state = 'a'
    @classmethod
    def change(cls):
        cls.state = 'changed'
print singleton.state
singleton.change()
print singleton.state

Since new-style classes are just type objects, singleton class works just
fine as a state container.

A standalone dictionary can serve the same purpose, but the states have to
be accessed through __getitem__() instread of __getattribute__().

yyc

On Thu, Sep 30, 2010 at 09:27, Mark Erbaugh <mark at microenh.com> wrote:

> Would the following code be appropriate to implement a singleton instance?
>
>
> class Singleton(object):
>        """ class that will have only one instance in the application """
>
> singleton = Singleton()
> del Singleton
>
>
> The single instance of the class would be instantiated the first time the
> module is imported. It would be impossible for any other code to instantiate
> another instance.
>
> I had originally thought of a slightly shorter, but less Pythonic version
>
> class singleton(object)
>        """ note the non-standard lowercase class name """
>
> singleton = singleton()
>
>
>
> Comments are welcome.
>
> Mark
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20100930/b52b53d8/attachment-0001.html>


More information about the CentralOH mailing list