mmkw43
Posts: 554
Joined: Tue Dec 24, 2013 6:18 pm

def __init__(): -- no error

Mon Feb 29, 2016 12:54 am

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

User avatar
DougieLawson
Posts: 39304
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: def __init__(): -- no error

Mon Feb 29, 2016 8:55 am

The one or two underscores is a convention not a syntax requirement.

http://stackoverflow.com/questions/1301 ... -in-python
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: def __init__(): -- no error

Mon Feb 29, 2016 9:50 am

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.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

mmkw43
Posts: 554
Joined: Tue Dec 24, 2013 6:18 pm

Re: def __init__(): -- no error

Mon Feb 29, 2016 3:18 pm

yeah -- that's how I found out. anyway, just sharing.

Return to “Python”