How to use "__new__"?

Heiko Wundram modelnine at ceosg.de
Wed Mar 30 04:36:05 CEST 2005


Am Mittwoch, 30. März 2005 03:27 schrieb could ildg:
> Thank you.
> I'm clear after I read the doc:
> If __new__() returns an instance of cls, then the new instance's
> __init__() method will be invoked like "__init__(self[, ...])", where
> self is the new instance and the remaining arguments are the same as
> were passed to __new__().
>
> If __new__() does not return an instance of cls, then the new
> instance's __init__() method will not be invoked.
>
> __new__() is intended mainly to allow subclasses of immutable types
> (like int, str, or tuple) to customize instance creation.

Remember that __new__() can also be used to create singletons (to return a 
pre-existing instance in case some form of argument matches, for example):

class Singleton(object):
    __buffer = {}

    def __new__(cls,somearg):
        if somearg not in cls.__buffer:
            cls.__buffer[somearg] = super(cls,Singleton).__new__(cls)
        return cls.__buffer[somearg]

    def __init__(self,somearg):
        self.__somearg = somearg

    def __repr__(self):
        return "<Singleton: %s at %s>" % (self.__somearg,hex(id(self)))

>>> x = Singleton(1)
>>> y = Singleton(2)
>>> z = Singleton(1)
>>> print x
<Singleton: 1 at -0x4840d934>
>>> print y
<Singleton: 2 at -0x4840d914>
>>> print z
<Singleton: 1 at -0x4840d934>
>>> x is y
False
>>> x is z
True
>>> y is z
False

You could extend the above example quite easily to deal with deallocation (a 
reference to each created singleton is retained using the above class, 
always, as long as the program is running) and also to make it threadsafe or 
to disable initialization in case the singleton has already been initialized 
before.

-- 
--- Heiko.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050330/e7383130/attachment.pgp>


More information about the Python-list mailing list