When I developed a Python script with Pydev in Eclipse, I came across a phenomenon that automatically generates an empty __init__.py file when I create a new Pydev package, because it's a novice python, So I do not know what the role of this empty file, because there is nothing to write here, so I directly deleted the file, the result of my package icon automatically changed into a folder icon, this is how it happened!
The original python module has a __init__ in each package. PY file (This file defines the properties and methods of the package) and then some module files and subdirectories, if there are __init__.py in the subdirectory then it is the child of this package. When you import a package as a module (such as importing the Dom from XML ), you actually import its __init__. PY file.
A package is a __init__ with a special file . The directory of the PY. __init__. py The file defines the properties and methods of the package. It can be nothing but a blank file, but it must exist. If __init__. PY does not exist, this directory is just a directory, not a package, it can not be imported or contain other modules and nested package.
_init__.py file:
__init__.py controls the import behavior of the package. If __init__.py is empty, then nothing can be done simply by importing the package.
>>> Import Package1
>>> Package1.module1
Traceback (most recent):
File "D:/work space/python practice/mypractice/src/test.py", line 8, <module>
Aa=package1.module1
Attributeerror: ' Module ' object has no attribute ' Module1 '
We need to pre-import the Module1 in __init__.py:
#文件 __init__.py
Import Module1
Test:
>>> Import Package1
>>> Aa=package1.module1
>>> Print AA
There is also an important variable in __init__.py, called __all__. We sometimes take a trick of "import All", which is this:
From PackageName Import *
Import then imports the sub-modules and sub-packages that are registered in the __ALL__ list in the package __init__.py file into the current scope. Like what:
#文件 __init__.py
__all__ = ["Module1", "Module2", "SubPackage1", "SubPackage2"]
Test:
>>> from Package1 Import *
>>>
test1111111111111111111111
test222222
The __init__.py file is executed at import time.
The role of the __init__.py file in the Python module package