Next / Previous / Contents / Shipman's homepage

46.3. The .__new__() method

singleton.py
# - - -   S i n g l e t o n . _ _ n e w _ _

    def __new__(cls, *args, **kw):
        '''Instance factory.

          [ if cls is a key in Singleton.__classMap ->
              return the related value
            else ->
              Singleton.__classMap[cls]  :=  a new
                  object of class cls
              return that new object ]
        '''

This method is the factory method called whenever a subclass is instantiated. The method of this name is automatically a class method, so its first argument cls is the class being instantiated.

singleton.py
        #-- 1 --
        try:
            return Singleton.__classMap[cls]
        except KeyError:
            inst = Singleton.__classMap[cls] = object.__new__(cls)
            return inst