Assigning to self

Peter Otten __peter__ at web.de
Mon Jan 17 16:04:41 EST 2005


Frans Englich wrote:

>> > >>> 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.
> 
> Ahem, John I ment :)

You are right -- just put the initialization into the __new__() method,
then.

Peter




More information about the Python-list mailing list