I think that's true for your own methods, but there are certain special methods that do need the double underscore before and after (
http://www.rafekettler.com/magicmethods.html).
If you use a single underscore for your __init__ method then there won't be a syntax error but the method won't be called when you initialise an instance of your class.
See below.
Code: Select all
In [1]: class TestSingleUnderscore(object):
...: def _init_(self):
...: self.x = 1
...:
In [2]: class TestDoubleUnderscore(object):
...: def __init__(self):
...: self.x = 1
...:
In [3]: single = TestSingleUnderscore()
In [4]: double = TestDoubleUnderscore()
In [5]: single.x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-6a93332d6ce4> in <module>()
----> 1 single.x
AttributeError: 'TestSingleUnderscore' object has no attribute 'x'
In [6]: double.x
Out[6]: 1
The "single" method fails because the "_init_" method has not been run on initialisation, but it has for the "double" hence we are able to retrieve the variable value.