Can __new__ prevent __init__ from being called?
Michael Spencer
mahs at telcopartners.com
Tue Feb 15 17:16:57 EST 2005
Peter Hansen wrote:
> Felix Wiemann wrote:
>
>> Sometimes (but not always) the __new__ method of one of my classes
>> returns an *existing* instance of the class. However, when it does
>> that, the __init__ method of the existing instance is called
>> nonetheless, so that the instance is initialized a second time. For
>> example, please consider the following class (a singleton in this case):
>>
> [snip]
>
>> How can I prevent __init__ from being called on the already-initialized
>> object?
>
>
> Is this an acceptable kludge?
>
> >>> class C(object):
> ... instance=None
> ... def __new__(cls):
> ... if C.instance is None:
> ... print 'creating'
> ... C.instance = object.__new__(cls)
> ... else:
> ... cls.__init__ = lambda self: None
> ... return cls.instance
> ... def __init__(self):
> ... print 'in init'
> ...
> >>> a = C()
> creating
> in init
> >>> b = C()
> >>>
>
> (Translation: dynamically override now-useless __init__ method.
> But if that works, why do you need __init__ in the first place?)
>
> -Peter
Or this one: use an alternative constructor:
class C(object):
instance = None
@classmethod
def new(cls, *args, **kw):
if cls.instance is None:
print 'Creating instance.'
cls.instance = object.__new__(cls)
print 'Created.'
cls.instance.__init__(*args,**kw)
return cls.instance
def __init__(self):
print 'In init.'
>>> c = C.new()
Creating instance.
Created.
In init.
>>> c = C.new()
>>>
Michael
More information about the Python-list
mailing list