学习目标
- 理解Python模块和包的概念
- 学习如何创建和导入模块
- 掌握标准库模块的使用
- 学习如何使用包组织代码
学习内容
1. 模块的概念
模块是一个包含Python代码的文件,模块可以包含函数、类和变量,也可以包含可执行的代码。模块使你能够组织和重用代码。
创建模块
创建一个名为 mymodule.py
的文件:
# mymodule.pydef greet(name):return f"Hello, {name}!"PI = 3.14159
导入模块
使用 import
语句导入模块:
import mymoduleprint(mymodule.greet("Alice")) # 输出: Hello, Alice!
print(mymodule.PI) # 输出: 3.14159
使用 from ... import
语句导入模块的特定部分:
from mymodule import greet, PIprint(greet("Bob")) # 输出: Hello, Bob!
print(PI) # 输出: 3.14159
2. 标准库模块
Python标准库包含许多有用的模块,可以直接导入使用。以下是一些常用模块的示例:
math
模块
import mathprint(math.sqrt(16)) # 输出: 4.0
print(math.pi) # 输出: 3.141592653589793
datetime
模块
import datetimenow = datetime.datetime.now()
print(now) # 输出: 当前日期和时间
os
模块
import osprint(os.getcwd()) # 输出: 当前工作目录
print(os.listdir('.')) # 输出: 当前目录下的文件和文件夹
3. 包的概念
包是一个包含多个模块的目录。包通过在目录中包含一个名为 __init__.py
的特殊文件来创建。
创建包
创建一个包结构如下:
mypackage/__init__.pymodule1.pymodule2.py
在 module1.py
中定义一些函数和变量:
# mypackage/module1.pydef func1():return "Function 1"var1 = "Variable 1"
在 module2.py
中定义一些函数和变量:
# mypackage/module2.pydef func2():return "Function 2"var2 = "Variable 2"
导入包
使用 import
语句导入包:
import mypackage.module1
import mypackage.module2print(mypackage.module1.func1()) # 输出: Function 1
print(mypackage.module2.func2()) # 输出: Function 2
使用 from ... import
语句导入包的特定部分:
from mypackage.module1 import func1, var1
from mypackage.module2 import func2, var2print(func1()) # 输出: Function 1
print(var1) # 输出: Variable 1
print(func2()) # 输出: Function 2
print(var2) # 输出: Variable 2
今日任务
-
创建并使用模块:
- 创建一个名为
math_operations.py
的模块,定义一些数学运算函数(如加法、减法、乘法和除法)。
- 创建一个名为
# math_operations.pydef add(a, b):return a + bdef subtract(a, b):return a - bdef multiply(a, b):return a * bdef divide(a, b):if b != 0:return a / belse:return "Division by zero is undefined"
-
- 创建一个Python脚本,导入
math_operations
模块并调用这些函数。
- 创建一个Python脚本,导入
# math_operations.pydef add(a, b):return a + bdef subtract(a, b):return a - bdef multiply(a, b):return a * bdef divide(a, b):if b != 0:return a / belse:return "Division by zero is undefined"
-
使用标准库模块:
- 编写代码,使用
math
模块计算一个数的平方根和圆的面积。
- 编写代码,使用
# math_example.pyimport mathnumber = 16
radius = 5sqrt_value = math.sqrt(number)
circle_area = math.pi * radius ** 2print(f"The square root of {number} is {sqrt_value}") # 输出: The square root of 16 is 4.0
print(f"The area of the circle with radius {radius} is {circle_area}") # 输出: The area of the circle with radius 5 is 78.53981633974483
-
- 编写代码,使用
datetime
模块获取当前日期和时间,并格式化输出。
- 编写代码,使用
# datetime_example.pyimport datetimenow = datetime.datetime.now()formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")print(f"Current date and time: {formatted_date}") # 输出: Current date and time: 2024-07-01 10:00:00
-
- 编写代码,使用
os
模块获取当前工作目录并列出当前目录下的文件和文件夹。
- 编写代码,使用
# os_example.pyimport oscurrent_directory = os.getcwd()
files_and_folders = os.listdir('.')print(f"Current working directory: {current_directory}") # 输出当前工作目录
print("Files and folders in the current directory:")
for item in files_and_folders:print(item)
-
创建并使用包:
- 创建一个名为
utilities
的包,其中包含两个模块:string_utils.py
和file_utils.py
。
- 创建一个名为
utilities/__init__.pystring_utils.pyfile_utils.py
-
- 在
string_utils.py
中定义一些字符串操作函数(如大写转换、小写转换)。
- 在
# utilities/string_utils.pydef to_uppercase(s):return s.upper()def to_lowercase(s):return s.lower()
-
- 在
file_utils.py
中定义一些文件操作函数(如读取文件内容、写入文件)。
- 在
# utilities/file_utils.pydef read_file(file_path):with open(file_path, 'r') as file:return file.read()def write_file(file_path, content):with open(file_path, 'w') as file:file.write(content)
-
- 创建一个Python脚本,导入
utilities
包并调用这些函数。
- 创建一个Python脚本,导入
# main_utilities.pyfrom utilities.string_utils import to_uppercase, to_lowercase
from utilities.file_utils import read_file, write_file# 使用字符串操作函数
s = "Hello, World!"
print(to_uppercase(s)) # 输出: HELLO, WORLD!
print(to_lowercase(s)) # 输出: hello, world!# 使用文件操作函数
file_path = 'example.txt'
content = "This is a test file."# 写入文件
write_file(file_path, content)# 读取文件
read_content = read_file(file_path)
print(read_content) # 输出: This is a test file.