Python module package __init__.py role file (reprint)

Django development has to do with more than a year, but did not pay attention to the basic meaning of python module __init__.py file exists, the chance to see its introduction daylights scared, this document is too important

module package:

package usually total is a directory, headed directory is a file __init__.py. Then some module files and subdirectories, if there are subdirectories __init__.py then it is sub-packages this package. It is almost like this:

Package1 / __init__.py module1.py Module2.py Package2 / __init__.py module1.py Module2.py
we can import a package this way:

Import Package1
or transferred to a sub-modules and sub-package:

from Package1 Import Module1from Packag1.Package2 Package1 import Package2import Packag1.Module1import
can drill down several layers of packet structure:

from Package1.Package2 Import Module1import Package1.Package2.Module1
almost so be it, I think, the essence of the package should be in the file __init__.py of.

__init__.py files:

__init__.py import controls the behavior of the package. If __init__.py is empty, then just import the package is what can be done.

>>> import Package1 >>> Package1.Module1Traceback (most recent call last): File "<pyshell # 1>", line 1, in Package1.Module1AttributeError:? 'Module' object has no attribute 'Module1'
we need _ _init__.py introduced in advance in the Module1:

# file __init __ pyimport Module1.
test:

>>> >>> Package1.Module1 the Package1 import <Module1 'Package1.Module1' from 'Module.pyc'>
__init__.py there a important variable, called __all__. We sometimes make a move out of "Import All", which is this:

from PackageName import *
Then import will be registered in the package __init__.py file __all__ sub-modules and sub-list of packages into the current scope Come. For example:

. # File __init __ py__all__ = [ 'Module1' , 'Module2', 'Package2']
Test:

>>> >>> Module2 from the Package1 Import * <Module1 '

Reproduced in: https: //www.cnblogs.com/licheng/archive/2010/12/06/1897426.html

Guess you like

Origin blog.csdn.net/weixin_33898233/article/details/93801094