跟着博主学Python,今天我们来到了第九天的学习,模块化编程的概念。Python作为一门编程语言,本身就是用于对模块以及各种包的使用来达到我们自己想到创作的目的。所以今天博主就给大家盘点一下有关于各种常见的包以及如何进行导入的。
Module,模块
定义一个名为 math_utils.pymath\_utils.pymath_utils.py 的模块:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
import 模块名 [as 模块新名字1]
导入一个模块到当前程序
from 模块名 import 模块属性名 [as 属性新名]
导入一个模块内部的部分属性到当前程序
from 模块名 import *
导入一个模块内部的全部属性到当前程序
import math_utils
print(math_utils.add(3, 5)) # 输出: 8
print(math_utils.subtract(10, 4)) # 输出: 6
也可以使用 from...importfrom ... importfrom...import 导入特定内容:
from math_utils import add
print(add(3, 5)) # 输出: 8
__file__ 绑定模块的路径
__name__ 绑定模块的名称
如果是主模块(首先启动的模块)则绑定 '__main__'
如果不是主模块则 绑定 xxx.py 中的 xxx 这个模块名
Python 的模块可以分为系统模块、自定义模块和第三方模块
Pytho内置的模块,安装Python时已包含,提供基础功能,比如数学运算、文件操作、网络通信等。
特点
import
即可使用。模块 | 功能 | 官方文档 |
---|---|---|
math |
数学运算 | https://docs.python.org/zh-cn/3.12/library/math.html |
os |
操作系统接口 | https://docs.python.org/zh-cn/3.13/library/os.html |
os.path |
路径相关 | https://docs.python.org/zh-cn/3.13/library/os.path.html |
datetime |
日期和时间 | https://docs.python.org/zh-cn/3.13/library/datetime.html |
random |
随机数生成 | https://docs.python.org/zh-cn/3.13/library/random.html |
time |
时间 | https://docs.python.org/zh-cn/3.13/library/time.html |
random模块:
import random
random.randint(1, 6) # random.randint(a,b) 生产 a~b的随机整数
random.randint(1, 6)
random.random() # random.random 生成包含0 但不包含1 的浮点数
random.choice("ABCD") # 从一个序列中,随机返回一个元素
random.choice("ABCD")
L = [1, 2, 3, 6, 9]
random.choice(L)
random.shuffle(L) # random.shuffer(x) # 把列表X 打乱
print(L)
随机生成密码:
import random
import time
## 生成 n 位的数字密码
def get_random_password(n):
r_str = ''
for _ in range(n):
r_str += str(random.randint(0, 9))
return r_str
## 生成 n 位的数字和字母组成的密码
charactors = '0123456789abcdefghijklmnopqrstwuxyz'
def get_random_password2(n):
r_str = ''
for _ in range(n):
r_str += random.choice(charactors)
return r_str
print(get_random_password(6))
print(get_random_password(6))
time.sleep(2)
print(get_random_password2(10))
time模块:
import time
time.time() # 返回当前时间的时间戳
time.ctime() #返回当前的UTC 时间的字符串
t1 = time.localtime() # 返回当前的本地时间元组
time.sleep(3) # 让程序睡眠 n 秒
time.strftime("%Y-%m-%d", t1) # 格式化时间
time.strftime("%y-%m-%d", t1)
time.strftime('%Y-%m-%d %H:%M:%S', t1)
os模块:
# 1. os.getcwd(): 获取当前工作目录
import os
current_directory = os.getcwd()
print("当前工作目录:", current_directory)
# 2. os.chdir(path): 改变当前工作目录
new_directory = "F:\\01.AI07.深度学习框架\\00.上课课件"
os.chdir(new_directory)
print("工作目录已更改为:", os.getcwd())
# 3. os.listdir(path='.'): 返回指定目录下的所有文件和目录列表
directory_path = "."
files_and_dirs = os.listdir(directory_path)
print("指定目录下的文件和目录列表:", files_and_dirs)
# 4. os.mkdir(path): 创建目录
new_directory = "new_folder"
os.mkdir(new_directory)
print(f"目录 '{new_directory}' 已创建")
# 5. os.rmdir(path): 删除目录
directory_to_remove = "new_folder"
os.rmdir(directory_to_remove)
print(f"目录 '{directory_to_remove}' 已删除")
# 6. os.remove(path): 删除文件
file_to_remove = "example.txt"
os.remove(file_to_remove)
print(f"文件 '{file_to_remove}' 已删除")
由社区或公司开发,通过包管理工具(如pip
)安装,用于实现更高级或更具体的功能,如数据科学、图像处理、网络爬虫等。
那这可就太多了~这里随便举的例子
模块 | 功能 | 示例 |
---|---|---|
numpy |
数值计算 | 科学运算、矩阵操作 |
pandas |
数据分析 | 数据清洗与处理 |
matplotlib |
数据可视化 | 绘制图表 |
requests |
HTTP请求处理 | 爬取网页内容,调用API |
flask |
Web应用框架 | 快速搭建Web服务 |
安装模块:
pip install numpy pandas requests
使用:
# numpy 模块
import numpy as np
array = np.array([1, 2, 3])
print(array.mean()) # 输出: 平均值 2.0
# pandas 模块
import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})
print(df)
# requests 模块
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json())
创建一个utils.py
文件:
# utils.py
def add(a, b):
return a + b
def greet(name):
return f"Hello, {name}!"
创建一个main.py
文件,并导入自定义模块:
# main.py
import utils
print(utils.add(3, 5)) # 输出: 8
print(utils.greet("Alice")) # 输出: Hello, Alice!
假设目录结构如下:
project/
utils/
__init__.py
math_utils.py
main.py
在main.py
中:
from utils.math_utils import add
print(add(3, 5)) # 输出: 8
Package
定义:
作用:用于组织模块的集合,形成层次化的结构,便于管理大型项目。
结构:
my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
import
关键字可以导入包和子包,以访问其中的模块和内容。 # 同模块的导入规则
import 包名 [as 包别名]
import 包名.模块名 [as 模块新名]
import 包名.子包名.模块名 [as 模块新名]
from 包名 import 模块名 [as 模块新名]
from 包名.子包名 import 模块名 [as 模块新名]
from 包名.子包名.模块名 import 属性名 [as 属性新名]
# 导入包内的所有子包和模块
from 包名 import *
from 包名.模块名 import *
参考案例:
# 导入包中的模块
import matplotlib.pyplot as plt
# 导入子包中的模块
from sklearn.linear_model import LinearRegression
一般来讲是要有的,如果没有这个文件也可以。
__init__.py\_\_init\_\_.py__init__.py 用于初始化Python包或模块,作用有:
__all__
变量明确指定从包中可以导入哪些模块,从而限制包的公开接口。__init__.py
中定义的变量和函数可以在包的模块中共享。__init__.py
文件中批量导入模块,这些模块可以更方便地使用。示例代码:
# __init__.py 文件示例
# 1. 批量导入系统模块
import os
import sys
import datetime
# 2. 定义包级别的变量
package_variable = "This is a package variable"
# 3. 控制包的导入行为
__all__ = ['module1', 'module2']
# 4. 执行初始化代码
print("Initializing mypackage")
# 注意:这个代码会在包被导入时执行
# 5. 导入包内的模块
from . import module1
from . import module2
模块 | 包 |
---|---|
一个Python文件 | 一个包含__init__.py 的文件夹 |
提供基本功能单元 | 用于组织多个模块 |
文件名为.py |
目录名 |
总的来说包就是一个在python中封装好了具有功能的,包含有一个__init__初始化文件的一个文件夹,我们可以调用其中的函数或者文件进行使用,不必我们再去写程序来实现其功能。而模块呢,主要是里面的.py文件,具体里面可以写类,类方法,或者直接写一个功能函数。但是呢俩者使用的时候可以直接用import来导入我们需要使用的函数或者方法所在的地方。