__init__.py function in Python package

Source: Internet
Author: User

During the creation of the Python package, the IDE creates a __init__.py file in the package root directory, which is empty by default. The directory structure is as follows:

The package tree structure under Pycharm:

The directory structure in the Finder:

As you can see from the directory in the Finder, each package is actually a directory, so how does the IDE recognize it as a package? Yes, the first function of __init__.py is the package 's identity , which, if not, is not considered to be a catalog.

The packages and modules in Python are imported in two ways: precise import and fuzzy import:

Precise import:

 from Import Pack1class Import Root.Pack1.Pack1Class

Fuzzy import:

 from Import *

The modules in the fuzzy import are defined by __all__, and another function of __init__.py is to define the __all__ in the package, which is used to blur the import , such as __init__.py:

__all__ = ["pack1class","pack1class1"]

Called Outside the package:

 from Import *= Pack1class.pack1_aa ("Alvin") A.printname () 

__init__.py is first a python file, and all can also be used to write Python modules , but it is not recommended to do so, try to ensure that __init__.py is light enough:

__init__.py:

__all__= ["Pack1class","Pack1class1","Init_aa"]class init_aa:def __init__(self,name): Self.name=namedefgreeting (self):Print("Hello", Self.name)

Called in the test:

 from Import *= Init_aa ("test") b.greeting ()

Summarize:

As can be seen from the above example, the main function of __init__.py is:

1. The identity of the package in Python cannot be deleted

2. Define __all__ for fuzzy import

3. Writing Python code (not recommended to write Python modules in __init__, you can create additional modules in the package to write, as far as possible to ensure __init__.py simple)

__init__.py function in Python 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.