changing how instances are "created"

John Roth newsgroups at
Mon Jun 13 01:41:21 CEST 2005

"newseater" <kbilsted at> wrote in message 
news:1118617483.215438.318980 at
> Hello. I need to be able to control how objects are created. Sometimes
> when creating an object, i want to reuse another object instead. I've
> searched for factory method implementations and singleton
> implementations. They were too much of a hack!
> My first attempt of doing this was to play around with the __new__()
> method. But i didn't quite succed. Then i came up with making a static
> method which can create my instances or re-use other instances.
> However, the below code I cannot get to work :(
> class Creator
> def createInstance(cls, *args, **kwargs):
> anewinstance = cls.__new__(cls, *args, **kwargs)
> anewinstance.__init__(*args, **kwargs)
> return anewinstance
> createInstance = staticmethod(createInstance)
> can anyone help??

__new__ is the proper way to do this, but making it work
is a bit tricky. If you could post the code you tried to
get to work for __new__(), we could critique it.

The current documentation is in 3.3.1 of the Python
Reference Manual (Python 2.4 version). In earlier
versions, there were a couple of other documents
that did a better (IMO) job of explaining things.

The trick is that __new__ must return an instance.
It can be a newly created instance (and the doc shows
how to do this) or an existing instance of any new style

By the way - when you post code, please use spaces
for indentation. There are a number of popular mail
clients that don't play fair with tabs, and people using
these clients will frequently ignore code that isn't
properly indented.

John Roth

More information about the Python-list mailing list