Sunday, August 17, 2014

Python Classes and the__init__ method (not the _init_ method)

Can you tell the difference between "init"s in the title? It's hard to see and in some cases, impossible.

I was doing an exercise on Codecademy and it failed to mention one teeny, tiny thing. When you write the function/method/constructor "__init__" inside a class, you must use double underscores, not single. Otherwise, when you try to initialize your object, you'll get an error message.

On Codecademy, you can't tell the difference between single and double underscores by looking at the screen. Only because of StackOverflow did I figure out the problem. If you don't believe StackOverflow, check out MIT's Python MOOC as well.

So what is __init__? Codecademy refers to it  as a function and someone in StackOverflow differentiated between init as a method and a constructor. Call it whatever you want. In the Python documentation, it's referred to as a "special method" which initializes the object. In C#, that would be a constructor. 

Unfortunately, I could not find any other documentation to highlight the fact that double underscores are required. If you search for this problem, you'll see many people have been hindered by this issue. For now, I'll accept that this is the way it is and I'll append a note to this post if I ever find anything official on the matter.

No comments:

Post a Comment