The role of the __init__.py file in the Python module package

Source: Internet
Author: User

package1/__init__.py module1.py module2.py package2/__init__.py module1.py module2.py

We can import a package like this:

From Package1 import Module1

From Package1 import Package2

Import Packag1.module1

Import Packag1.package2

__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 "<pyshell#1>", line 1, in?

Package1.module1attributeerror: ' Module ' object has no attribute ' Module1 '

We need to pre-import the Module1 in __init__.py:

#文件 __init__.py

Import Module1

>>> Import Package1

>>> Package1.module1

<module ' Package1.module1 ' from ' Module.pyc ' >


__init__.py, called __all__. import all

from packagename import * 

example:  
#文件 __init__.py

__all__ = [' Module1 ', ' Module2 ', ' Package2 ']




The role of the __init__.py file in the Python module package

Related Article

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.