Package: Placing a module that solves a class of problems in the same directory creates a package
To get a better understanding of the package, we'll simulate creating a package
ImportOsos.makedirs ('Glance/api') Os.makedirs ('Glance/cmd') Os.makedirs ('glance/db') Lis= [Open ('glance/__init__.py','W'), open ('glance/api/__init__.py','W'), open ('glance/api/policy.py','W'), open ('glance/api/versions.py','W'), open ('glance/cmd/__init__.py','W'), open ('glance/cmd/manage.py','W'), open ('glance/db/__init__.py','W'), open ('glance/db/models.py','W')]map (LambdaF:f.close (), Lis)
The '. py ' file we create is equivalent to a module, which can be used to write a simple function for testing.
Import of modules in packages
# through the package name. Directory. Module names the module import inside the package Import Glance.api.policy as Policypolicy.get ()
The role of the __init__.py file
# This file is executed when a __init__.py file is imported into the package under each package f = open ('glance/__init__.py' W ', encoding='utf-8') f.write ("print (' This is glance/__init__.py ')f.close ()import glance # Print This is glance/__init__.py
So when we create a package ourselves, we can take advantage of the __init__.py in the completion of the inner layer of the import work.
"""You can therefore write the import code for the next layer of the package in advance by writing the __init__.py file from the Glance Import API from the Glance import cmd from glance Import DB"""F= Open ('glance/api/__init__.py','W', encoding='Utf-8') F.write ("print (' This is glance/api/__init__.py ')") F.close ()#executed the From glance Import API and then executed the __init__.py under the APIImportGlance#Print This is glance/api/__init__.py#__init__.py under API write good from GLANCE.API import PolicyImportGlanceglance.api.policy.get ()#Print from policy.py"""by this way, in the __init__.py file to write the next layer of all the content of the import code only need to import the package name can be imported into all the following modules"""
There are generally two ways to import: Absolute path Import and relative path import
1, Absolute path import
# Absolute Path Import when writing import code in a __init__.py file, use an absolute path, such as: From GLANCE.API import Policy" " Advantage: After importing, It can be used both inside and outside the package, and intuitively. disadvantage: Can not move, otherwise you will find the wrong path """
2, relative path import
# relative path Import when writing import code in a __init__.py file, use a relative path, such as: From. Import Policy """ '. ' Represents the current directory advantages: You can move, as long as you can find the package, the inside of the module will be able to import the disadvantage: The package can not be used in the other modules, the implementation of imports will be error " " "
Python Module Package