第8天:模块和包

学习目标

  • 理解Python模块和包的概念
  • 学习如何创建和导入模块
  • 掌握标准库模块的使用
  • 学习如何使用包组织代码
学习内容
1. 模块的概念

模块是一个包含Python代码的文件,模块可以包含函数、类和变量,也可以包含可执行的代码。模块使你能够组织和重用代码。

创建模块

创建一个名为 mymodule.py 的文件:

# mymodule.py

def greet(name):
    return f"Hello, {name}!"

PI = 3.14159
 
导入模块

使用 import 语句导入模块:

import mymodule

print(mymodule.greet("Alice"))  # 输出: Hello, Alice!
print(mymodule.PI)  # 输出: 3.14159

使用 from ... import 语句导入模块的特定部分:

from mymodule import greet, PI

print(greet("Bob"))  # 输出: Hello, Bob!
print(PI)  # 输出: 3.14159
2. 标准库模块

Python标准库包含许多有用的模块,可以直接导入使用。以下是一些常用模块的示例:

math 模块
import math

print(math.sqrt(16))  # 输出: 4.0
print(math.pi)  # 输出: 3.141592653589793
datetime 模块
import datetime

now = datetime.datetime.now()
print(now)  # 输出: 当前日期和时间
os 模块
import os

print(os.getcwd())  # 输出: 当前工作目录
print(os.listdir('.'))  # 输出: 当前目录下的文件和文件夹
3. 包的概念

包是一个包含多个模块的目录。包通过在目录中包含一个名为 __init__.py 的特殊文件来创建。

创建包

创建一个包结构如下:

mypackage/
    __init__.py
    module1.py
    module2.py

module1.py 中定义一些函数和变量:

# mypackage/module1.py

def func1():
    return "Function 1"

var1 = "Variable 1"

module2.py 中定义一些函数和变量:

# mypackage/module2.py

def func2():
    return "Function 2"

var2 = "Variable 2"
导入包

使用 import 语句导入包:

import mypackage.module1
import mypackage.module2

print(mypackage.module1.func1())  # 输出: Function 1
print(mypackage.module2.func2())  # 输出: Function 2

使用 from ... import 语句导入包的特定部分:

from mypackage.module1 import func1, var1
from mypackage.module2 import func2, var2

print(func1())  # 输出: Function 1
print(var1)  # 输出: Variable 1
print(func2())  # 输出: Function 2
print(var2)  # 输出: Variable 2
今日任务
  1. 创建并使用模块:

    • 创建一个名为 math_operations.py 的模块,定义一些数学运算函数(如加法、减法、乘法和除法)。
# math_operations.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b != 0:
        return a / b
    else:
        return "Division by zero is undefined"
    • 创建一个Python脚本,导入 math_operations 模块并调用这些函数。
# math_operations.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b != 0:
        return a / b
    else:
        return "Division by zero is undefined"
  1. 使用标准库模块:

    • 编写代码,使用 math 模块计算一个数的平方根和圆的面积。
# math_example.py

import math

number = 16
radius = 5

sqrt_value = math.sqrt(number)
circle_area = math.pi * radius ** 2

print(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.py

import datetime

now = 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.py

import os

current_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)
  1. 创建并使用包:

    • 创建一个名为 utilities 的包,其中包含两个模块:string_utils.pyfile_utils.py
utilities/
    __init__.py
    string_utils.py
    file_utils.py
    • string_utils.py 中定义一些字符串操作函数(如大写转换、小写转换)。
# utilities/string_utils.py

def to_uppercase(s):
    return s.upper()

def to_lowercase(s):
    return s.lower()
    • file_utils.py 中定义一些文件操作函数(如读取文件内容、写入文件)。
# utilities/file_utils.py

def 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 包并调用这些函数。
# main_utilities.py

from 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.

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值