[Python functions and modules] (13) talk about __init__.py

Write in front : The following names of packages and modules and their methods can be found in the blog: https://www.cnblogs.com/ac-chang/p/12673223.html

 

1. Note the double underscore in English half-width

2. Turn a folder into a module

3. The import package actually imports its __init__.py

4. Generally empty, you can import the required modules in batches

 

The __init__.py file is generally empty, and it plays a big role when it contains multiple sub-files under one package

For example : directly import the pay package, and want to call the method of the module in its sub-package

import pay

pay.alipay.pay()

 

The program reports an error : It says that the 'alipay' attribute was not found under the 'pay' module

 

However, alipay is actually a subfile of pay . To find the method of the module in the subfile , you need to write the following code in __init__.py under pay:

from . import alipay
from . import wechat_pay

 

This is the example before running again, the program continues to report errors , but this time it is reported that the 'pay' attribute cannot be found under 'pay.alipay'

 

This is because alipay is a package with tools module under the package, and the pay () method is under the tools module . At this time, the following code needs to be written in __init__.py under alipay:

from .tools import pay
from .tools import get_status

 

Similarly, __init__.py under wechat_pay writes the following code:

from .tools import pay

 

Run the program again and execute it correctly

 

Guess you like

Origin www.cnblogs.com/ac-chang/p/12673451.html