changing how instances are "created"

Robert Kern rkern at ucsd.edu
Sun Jun 12 19:14:36 EDT 2005


newseater wrote:
> 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)

You want a classmethod, not a staticmethod.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list