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):
[color=blue][color=green][color=darkred]
>>> class C(object):[/color][/color][/color]
.... instance = None
.... def __new__(cls):
.... if C.instance is None:
.... print 'Creating instance.'
.... C.instance = object.__new__( cls)
.... print 'Created.'
.... return cls.instance
.... def __init__(self):
.... print 'In init.'
....[color=blue][color=green][color=darkred]
>>> C()[/color][/color][/color]
Creating instance.
Created.
In init.
<__main__.C object at 0x4062526c>[color=blue][color=green][color=darkred]
>>> C()[/color][/color][/color]
In init. <---------- Here I want __init__ not to be executed.
<__main__.C object at 0x4062526c>[color=blue][color=green][color=darkred]
>>>[/color][/color][/color]
How can I prevent __init__ from being called on the already-initialized
object?
I do not want to have any code in the __init__ method which checks if
the instance is already initialized (like "if self.initialize d: return"
at the beginning) because that would mean I'd have to insert this
checking code in the __init__ method of every subclass.
Is there an easier way than using a metaclass and writing a custom
__call__ method?
--
Felix Wiemann -- http://www.ososo.de/
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):
[color=blue][color=green][color=darkred]
>>> class C(object):[/color][/color][/color]
.... instance = None
.... def __new__(cls):
.... if C.instance is None:
.... print 'Creating instance.'
.... C.instance = object.__new__( cls)
.... print 'Created.'
.... return cls.instance
.... def __init__(self):
.... print 'In init.'
....[color=blue][color=green][color=darkred]
>>> C()[/color][/color][/color]
Creating instance.
Created.
In init.
<__main__.C object at 0x4062526c>[color=blue][color=green][color=darkred]
>>> C()[/color][/color][/color]
In init. <---------- Here I want __init__ not to be executed.
<__main__.C object at 0x4062526c>[color=blue][color=green][color=darkred]
>>>[/color][/color][/color]
How can I prevent __init__ from being called on the already-initialized
object?
I do not want to have any code in the __init__ method which checks if
the instance is already initialized (like "if self.initialize d: return"
at the beginning) because that would mean I'd have to insert this
checking code in the __init__ method of every subclass.
Is there an easier way than using a metaclass and writing a custom
__call__ method?
--
Felix Wiemann -- http://www.ososo.de/
Comment