What is __init__?

Tagged: , , ,

This topic was published by and viewed 1411 times since "". The last page revision was "".

Viewing 1 post (of 1 total)
  • Author

  • DevynCJohnson
    • Topics - 437
    • @devyncjohnson

    In Python, there are two kinds of "__init__". One is an initial function for a class and the other is a special file.

    The __init__ function in a class is used to execute some code when the class is called. For instance, in the Color-Kit program of mine (https://dcjtech.info/topic/color-kit/), the window is a class. In the class, the "__init__" function is used to define the window while other functions in the class define certain behaviors. The code in an __init__ function is needed to perform important tasks that must be executed when the class is called.

    More info - https://docs.python.org/3.4/tutorial/classes.html

    The "__init__.py" file is used with libraries and modules. For instance, I may have a script named "program.py" in a directory. In that same directory, I may have another directory named "library". Inside the library directory, I may have various Python libraries/modules. If a "__init__.py" file is in the directory, then this indicates that Python can look at these files when searching for a module that is to be imported. In other words, the "__init__.py" file declares the files in its directory to be importable packages/modules. So, in "program.py", I could have the code "from library import *" and all of the files in the "library" directory will be imported. The "__init__.py" file may be empty or contain code related to preparing the libraries/imports.

    More info - https://docs.python.org/3.4/tutorial/modules.html#packages

    Further Reading

Viewing 1 post (of 1 total)