Singleton in Python

This is just one way of achieving singleton in python.

>>> class Director(object):
…       _instance = None
…       def __new__(cls, *args, **kwargs):
…           if not cls._instance:
…               cls._instance = super(Director, cls).__new__(cls, *args, **kwargs)
…           return cls._instance

>>> d1=Director()
>>> d2=Director()
>>> id(d1)
3077730924L
>>> id(d2)
3077730924L

You can see that the id is the same for both the instances (d1 and d2).

Both d1 and d2 share the same instance of the Directory class.

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