Is there any way to call the init() method of a class only one time. Or how can I disable calling of init() when I create an object from a class?
-
You mean you want a singleton? – Mark Byers Oct 28 '11 at 16:32
-
5`__init__` will always be called upon object construction. That is what it is there for. If you are trying to have it called only once, then there is likely a flaw in your logic. If you post what you are trying to achieve we may be able to help you come up with a more correct solution – Matt Williamson Oct 28 '11 at 16:34
-
The purpose of `__init__` is to fire when you create an instance of a class. Be more specific about what you are trying to do here. – Will Oct 28 '11 at 16:34
-
I think he wants to avoid `Foobar().__init__( ... )`. – hochl Oct 28 '11 at 16:36
-
is this something you want to run the first time you create an object, and then never again, or is it something you want to run at class creation time? If the latter, try having a look at Metaclasses. The following SO answer is a great intro to Metaclasses: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/6581949#6581949 – Oct 28 '11 at 19:21
4 Answers
If you want a singleton, where there is only ever one instance of a class then you can create a decorator like the following as gotten from PEP18:
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
pass
Try it out:
>>> a = MyClass()
>>> b = MyClass()
>>> a == b
True

- 39,165
- 10
- 64
- 72
There's no direct way to disable __init__
, but there are a few ways to work around this. One of them is having a flag:
class Class:
_init_already = False
__init__(self):
if not Class._init_already:
...
Class._init_already = True
But this is ugly. What is it that you are really trying to accomplish?

- 30,618
- 31
- 128
- 208
You shouldn't put anything in __init__()
that you only want to run once. Each time you create an instance of a class __init__()
will be run.
If you want to customize the creation of your class you should look into creating a metaclass. Basically, this lets you define a function that is only run once when the class is first defined.

- 202,379
- 35
- 273
- 306
The init method will always be called however you could create another method called run() or something, that you call after creating the object, optionally.
foo = ClassName()
foo.run() # replacement for __init__
foo2 = ClassName()