Assigning to self

Frans Englich frans.englich at telia.com
Mon Jan 17 21:55:33 CET 2005


On Monday 17 January 2005 19:02, Peter Otten wrote:
> Frans Englich wrote:
> > What the code attempts to do is implementing a, to the API user,
> > transparent memory-saver by ensuring that no more than one instance of
> > the class foo exists for a particular id. E.g, the user can simply
> > "create" an instance and if one not already exists, it is created.
>
> By the time __init__() is called, a new Foo instance has already been
>
> created. Therefore you need to implement Foo.__new__().  E. g.:
> >>> class Foo(object):
>
> ...     cache = {}
> ...     def __new__(cls, id):
> ...             try:
> ...                     return cls.cache[id]
> ...             except KeyError:
> ...                     pass
> ...             cls.cache[id] = result = object.__new__(cls, id)
> ...             return result
> ...     def __init__(self, id):
> ...             self.id = id
> ...     def __repr__(self):
> ...             return "Foo(id=%r)" % self.id
> ...

I'm not sure, but I think this code misses one thing: that __init__ is called 
each time __new__ returns it, as per the docs Peter posted. 


Cheers,

		Frans




More information about the Python-list mailing list