Page 1 of 1

def __init__(): -- no error

Posted: Mon Feb 29, 2016 12:54 am
by mmkw43
I don't know if it means anything to anybody but I had the initialize method in one of my classes with just one underscore each by mistake (rather than 2) and there is no error thrown when you do that. fyi

Re: def __init__(): -- no error

Posted: Mon Feb 29, 2016 8:55 am
by DougieLawson
The one or two underscores is a convention not a syntax requirement.

http://stackoverflow.com/questions/1301 ... -in-python

Re: def __init__(): -- no error

Posted: Mon Feb 29, 2016 9:50 am
by elParaguayo
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.

Re: def __init__(): -- no error

Posted: Mon Feb 29, 2016 3:18 pm
by mmkw43
yeah -- that's how I found out. anyway, just sharing.