Is there any way to avoid calling __init__
on a class while initializing it, such as from a class method?
I am trying to create a case and punctuation i
A trick the standard pickle and copy modules use is to create an empty class, instantiate the object using that, and then assign that instance's __class__
to the "real" class. e.g.
>>> class MyClass(object):
... init = False
... def __init__(self):
... print 'init called!'
... self.init = True
... def hello(self):
... print 'hello world!'
...
>>> class Empty(object):
... pass
...
>>> a = MyClass()
init called!
>>> a.hello()
hello world!
>>> print a.init
True
>>> b = Empty()
>>> b.__class__ = MyClass
>>> b.hello()
hello world!
>>> print b.init
False
But note, this approach is very rarely necessary. Bypassing the __init__
can have some unexpected side effects, especially if you're not familiar with the original class, so make sure you know what you're doing.