Kaushik
Kaushik

Reputation: 1324

Can __init__() function in python be invoked at a different moment than at object creation?

Is it possible to invoke __init__() function explicitly? Or the function is always invoked when an object of the class is instantiated?

Upvotes: 0

Views: 96

Answers (3)

Paulo Scardine
Paulo Scardine

Reputation: 77339

__init__ is invoked on instantiation. When you call some_instance = SomeClass(a, b), it is called with self, a and b as arguments.

Python has the "we are all consenting adults" motto, so yes, you can - but every time you call double-underscored methods you should really know what you are doing and you have to face the consequences if it breaks something.

Most classes are not designed to have __init__ called after instantiation, and it would be an odd design; if you are tempted to call some_instance.__init__(*args) in order to recycle an object, just get a new instance calling SomeClass(*args) - calling __init__ is not guaranteed to reset state from an existing instance, gambling on this would be bad design.

I'm not aware of any use case for calling __init__ explicitly except for overriding the parent class __init__ using super.

Upvotes: 4

Aaron Digulla
Aaron Digulla

Reputation: 328754

Python is a very lenient language which also means you can do some things that you shouldn't. So while __init__() is a method (which means you can call it directly, like any other method), the results vary from class to class. Some classes initialized all their state in __init__(), so calling it again effectively resets the class. Other classes behave differently and there is no guarantee that a class will always behave in one way or the other.

Usually, this question comes up when you need a two-step init (i.e. create the class, so some setup and then really init it). Create a new init() method for that:

a = A()
a.setFoo(foo)
a.init()

Similarly, if your class supports reset, add a reset() method.

Upvotes: 0

Rahul Tanwani
Rahul Tanwani

Reputation: 441

To start with, __init__ is not called whenever the object is created but instantiated. The job of object creation is of __new__, which is called before __init__, and hence __new__ is called the constructor of a class. Please refer __new__ for detailed explanation. Coming back to question, Yes it is possible to do so. Here is the quickie to demonstrate:

>>> class Test(object):
...     def __init__(self):
...         print "instantiating object"
... 
>>> t = Test()
instantiating object
>>> t.__init__()
instantiating object

Thanks!

Upvotes: 1

Related Questions