Returning other instance from __init__

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Mar 17 01:17:07 EDT 2007


On Thu, 15 Mar 2007 04:33:01 +0000, Paulo da Silva wrote:

> I would like to implement something like this:
> 
> class C1:
> 	def __init__(self,xxx):
> 		if ... :
> 			self.foo = foo
> 			self.bar = bar
> 		else:
> 			self=C1.load(xxx)
> 
> 	def load(xxx):
> 		...
> 		return instance_of_C1
> 	load=staticmethod(load)
> 
> This does not seem correct. How can I do it?



Others have come up with other solutions which may or may not work, but
perhaps you can adapt this to do what you want.


class CachedClass(object):
    """Class that recycles cached instances.
    """
    _cache = {}
    def __new__(cls, ID):
        print "Calling constructor __new__ ..."
        if cls._cache.has_key(ID):
            print "Returning cached instance..."
            return cls._cache[ID]
        else:
            print "Creating new instance..."
            obj = super(CachedClass, cls).__new__(cls, ID)
            cls._cache[ID] = obj
            return obj
    def __init__(self, ID):
        print "Calling constructor __init__ ..."
        self.ID = ID



-- 
Steven




More information about the Python-list mailing list