Article Directory
Preface
1. Modules in python
- The python module is essentially a python file
- The file name of the custom python file must not conflict with the existing module
- Importing a module is essentially loading and executing the content of the module
1.1 Several ways to import modules
- method one
hello.py
digits='0123'
import hello
print(hello.digits)
输出:
0123
- Way two
hello.py ## 模块文件
digits='0123'
def info():
print('打印信息')
import hello
print(hello.digits)
hello.info()
输出:
0123
打印信息
- Way three
from hello import info
info()
输出:
打印信息
- Way Four
from hello import info as f
f()
输出:
打印信息
- Way Five
from hello import *
print(digits)
输出:
0123
1.2 Other information of the module
import sys
print(sys.path) ## 模块的查询路径
import hello
print(dir(hello)) ## 查看hello模块可以使用的变量和函数
print(hello.__doc__) ## 查看模块的说明文档
print(hello.__file__) ## 显示模块的绝对路径
print(hello.__name__) ## __name__当模块被导入时,显示的是模块的名称。
1.3 Special usage of name
hello.py file: When executed inside the module, the value of __name__ is __main__; when the module is imported, the value of __name__ is hello (module name)
digits='0123'
def info():
print('打印信息')
if __name__ == '__main__':
print(__name__)
The code that needs to be executed when the module is executed internally. When the module is imported, it is not executed.
import hello
print(hello.digits)
hello.info()
print(hello.__name__)
输出:
0123
打印信息
hello
2. Package management
- The package is essentially a directory containing the __init__.py file.
- The essence of importing the package is to execute the content init.py file of __init__.py in the package
print('正在加载__init__')
import sdk
输出:正在加载__init__
Ways to import packages
Create the python package sdk, create two sub-files age.py and name.py
age.py
def create():
print('name添加成功')
name.py
def create():
print('age添加成功')
- method one
from sdk import age
from sdk import name
age.create()
name.create()
输出:
age创建成功
name添加成功
- Way two
Need to add import information in the package __init__.py
from . import name
from . import age
import sdk
sdk.name.create()
sdk.age.create()
输出:
name添加成功
age创建成功