Python package__ init__. Function and usage analysis of PY

Time:2021-7-20

This article describes the python package__ init__. The function and usage of py. The details are as follows:

Package:

  • In order to organize modules well, multiple modules are combined into a package, so the package is used to store Python modules
  • A package is usually a folder. When a folder is used as a package, the folder needs to contain__ init__. Py file
  • __ init__. Py can be empty. It is generally used for some initialization or settings of the package__ all__ Value__ all__ It’s infrom … import * Statement__ all__ All modules defined in will be imported in from… Import *

Directory structure:image

Test1 Code:image

package_ test.__ init__. Py Code:image

Inner code:image

The test1 module of the import package and the inner module of the sub package are as follows:

from package_test import test1

from package_test.child_package import inner



#-----------------Results of operation:
run in package_test.__init__.py
import test1 done
run in inner

__ init__. Common uses of PY

  • Batch import the modules we need

__ init__ code:

image

B import package_ Test code:

import package_test

print(package_test.re,package_test.bs4)


#--------------
#Results of operation:
<module 're' from 'I:\python3\lib\re.py'> <module 'bs4' from 'I:\python3\lib\site-packages\bs4\__init__.py'>
  • __ all__, It is used to import all the modules. Different from the above__ all__ Only modules in the package can be imported:

Directory structure:

image

__ init__ code:


__all__=['test1']

B import package_ Test code:


from package_test import *

More about Python related content, interested readers can see our special topics: summary of Python function use skills, python object-oriented programming introduction and advanced tutorial, python data structure and algorithm tutorial, Python string operation skills summary, python coding operation skills summary and python introduction and advanced classic tutorial

I hope this article is helpful for Python programming.

Recommended Today

Spark open source new feature: catalyst optimizes process tailoring

Summary:In order to solve the problem of relying too much on hive, sparksql uses a new SQL optimizer to replace the optimizer in hive, which is catalyst. This article is shared from Huawei cloud community《Spark open source new feature: catalyst optimizes process tailoring》, author: hzjturbo. 1. Problem background The figure above shows the layout of […]