Python Singleton

#!/usr/bin/python

class Singleton( object ):
        instance = None
        def __new__( className, *args, **kargs):
                print 'Getting %s instance' % className.__name__
                if className.instance is None:
                        print 'Creating new %s object' % className.__name__
                        className.instance = object.__new__( className, *args, **kargs );
                return className.instance

        def __init__( self ):
                try:
                        self.initialized
                except:
                        self.init()

        def init( self ):
                print 'Initializing %s object' % self.__class__.__name__
                self.initialized = True

Singleton()
Singleton()
Singleton()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s