Fork me on GitHub

Thursday, December 3, 2009

Curious case of object initialization in python

While working on writing some Async code for CouchDb connector using Tornado webclient I used the code of AyncHTTPClient as a doc. Reading the code I found an interesting piece of initialization method. This may not be anything new for a lot of python people but for me I found this pattern interesting. I had used python long time back while it was in 2.5.x time and I came back to it recently to work on UNICEF project. So my knowledge of python may not be as sharp as knife :)

So lets jump into the code directly. The initialization method as I remember in python is __init__. For those unfamiliar with python __init__ is the first method called when an object is initialized. Or in other words a constructor. Similar to ruby's init method. Pretty simple right?

But checkout the __new__ method. A simple example of usage of __new__ method for singleton pattern in python.



So how is __new__ method different from __init__? As seen from example __new__ gives a complete control of the object I construct. So when initializing the object the order of calling is
1. You try to create an object --> 2. __new__ called if available to create an instance --> 3. object initialized using __init__. Also __new__ can return an instance of the class you are creating. __init__ only does the job of initializing it and does not return anything.

I know a lot of you may know about this already. But I wanted to share what I understood. Let me know if you think there is a better explanation or I have goofed up something.

No comments: