En Sun, 25 Mar 2007 23:34:51 -0300, manstey <[EMAIL PROTECTED]> escribió:
> I've realised after further testing and reading that I actually need > to do this: > >>>> dic_myinstances={} >>>> class MyClass(object): > def __new__(cls,id): > global dic_myinstances > if dic_myinstances.has_key(id): > return dic_myinstances[id] > else: > dic_myinstances[id] = super(MyClass, cls).__new__(cls, id) > return dic_myinstances[id] > def __init__(self,id): > print id > >>>> ins1 = MyClass('xx') > 'xx' >>>> ins2 = MyClass('yy') > 'yy' >>>> ins3 = MyClass('xx') > 'xx' >>>> ins3 is ins1 > True That's fine, but notice that __init__ is called even if the instance already exists. That's usually undesirable, and you can use a factory function instead: def MyClassFactory(id): inst = dic_myinstances.get(id) if inst is None: dic_myinstances[id] = inst = MyClass(id) return inst (Notice that no global statement is needed, even on your __new__) You can make it a static method if you wish. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list