F
Felix Wiemann
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):
.... 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.'
....Creating instance.
Created.
In init.
In init. <---------- Here I want __init__ not to be executed.
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.initialized: 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?
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):
.... 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.'
....Creating instance.
Created.
In init.
In init. <---------- Here I want __init__ not to be executed.
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.initialized: 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?