Python singleton using new-style class

The new-style class is the class that inherit from object or the new-style class.
The new-style class has __new__ method. When creating new instance, __new__ is called before __init__ and it would return the instance.

This is an example:

>>> class A(object):
...     _inst = None
...     def __new__(cls, *args, **kwargs):
...         if cls._inst is not None:
...             return cls._inst
...         cls._inst = object.__new__(cls, *args, **kwargs)
...         return cls._inst
...
>>> c = A()
>>> id(c)
142024844
>>> b = A()
>>> id(b)
142024844
>>> c.x = 1
>>> b.x
1
>>>

Author:

  • nattapon

Archives:

Powered by Django.