replacing one instance with another

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Mar 26 05:20:16 CEST 2007


En Sun, 25 Mar 2007 23:34:51 -0300, manstey <manstey at csu.edu.au> 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




More information about the Python-list mailing list