The role of the __init__.py file in Python2

Source: Internet
Author: User

The role of the __init__.py file in Python2:

1, Python each module of the package, must have a __init__.py file, with this file, we can import the module in this directory.

2. Other functions of __init__.py:

On a point, our __init__.py is empty. In fact, __init__.py inside can still have content, we import a package, actually imported its __init__.py file.

We can import other packages, or modules, in the __init__.py file.

Content of __init__.py:

Import Module1

Import Module11

Import Module12 This way, when we import this package, the __init__.py file runs automatically. To help us import so many modules, we do not need to write all the import statements in a file, but also reduce the amount of code. There is no need to import the module.

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"]

The role of the __init__.py file in Python2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.