Skip to content

🔧 Python 函数与模块

函数概述

函数是组织好的、可重复使用的代码块,用来实现单一或相关功能的代码段。函数能提高应用的模块性和代码的重复利用率。

💡 函数的好处: - 代码复用:避免重复编写相同的代码 - 模块化:将复杂问题分解为简单的小问题 - 易于维护:修改功能时只需要修改函数 - 易于测试:可以单独测试每个函数

📝 函数定义和调用

基本函数定义

python
# 定义函数
def greet():
    """简单的问候函数"""
    print("Hello, World!")

# 调用函数
greet()  # 输出: Hello, World!

# 带参数的函数
def greet_person(name):
    """带参数的问候函数"""
    print(f"Hello, {name}!")

greet_person("张三")  # 输出: Hello, 张三!

# 带多个参数的函数
def add_numbers(a, b):
    """计算两个数的和"""
    return a + b

result = add_numbers(3, 5)
print(f"3 + 5 = {result}")  # 输出: 3 + 5 = 8

参数类型

位置参数

python
def calculate_area(length, width):
    """计算矩形面积"""
    return length * width

area = calculate_area(5, 3)  # 位置参数
print(f"面积: {area}")  # 输出: 面积: 15

关键字参数

python
def create_profile(name, age, city="北京", occupation="学生"):
    """创建用户档案"""
    return f"姓名: {name}, 年龄: {age}, 城市: {city}, 职业: {occupation}"

# 使用关键字参数
profile1 = create_profile(name="张三", age=20)
profile2 = create_profile(name="李四", age=25, city="上海", occupation="工程师")
print(profile1)
print(profile2)

默认参数

python
def greet_with_title(name, title="先生"):
    """带默认参数的问候函数"""
    return f"你好,{title}{name}!"

# 使用默认参数
greeting1 = greet_with_title("张三")
greeting2 = greet_with_title("李四", "女士")
print(greeting1)  # 你好,先生张三!
print(greeting2)  # 你好,女士李四!

可变参数

python
# *args - 接收任意数量的位置参数
def sum_numbers(*args):
    """计算任意数量数字的和"""
    total = 0
    for num in args:
        total += num
    return total

result1 = sum_numbers(1, 2, 3)
result2 = sum_numbers(1, 2, 3, 4, 5)
print(f"结果1: {result1}")  # 结果1: 6
print(f"结果2: {result2}")  # 结果2: 15

# **kwargs - 接收任意数量的关键字参数
def create_user(**kwargs):
    """创建用户信息"""
    user_info = {}
    for key, value in kwargs.items():
        user_info[key] = value
    return user_info

user1 = create_user(name="张三", age=20, city="北京")
user2 = create_user(name="李四", age=25, city="上海", occupation="工程师")
print(f"用户1: {user1}")
print(f"用户2: {user2}")

参数组合

python
def complex_function(required_arg, default_arg="默认值", *args, **kwargs):
    """复杂的参数组合示例"""
    print(f"必需参数: {required_arg}")
    print(f"默认参数: {default_arg}")
    print(f"位置参数: {args}")
    print(f"关键字参数: {kwargs}")

complex_function("必需", "自定义", 1, 2, 3, name="张三", age=20)

🔄 返回值

基本返回值

python
def get_full_name(first_name, last_name):
    """返回完整姓名"""
    return f"{first_name} {last_name}"

full_name = get_full_name("张", "三")
print(f"完整姓名: {full_name}")

# 返回多个值(实际上是返回元组)
def get_name_and_age():
    """返回姓名和年龄"""
    return "张三", 20

name, age = get_name_and_age()
print(f"姓名: {name}, 年龄: {age}")

返回复杂数据结构

python
def analyze_text(text):
    """分析文本,返回统计信息"""
    words = text.split()
    return {
        "字符数": len(text),
        "单词数": len(words),
        "平均长度": sum(len(word) for word in words) / len(words) if words else 0
    }

analysis = analyze_text("Hello World Python Programming")
print(f"分析结果: {analysis}")

🎯 函数的高级特性

函数作为参数

python
def apply_operation(numbers, operation):
    """对数字列表应用操作"""
    return [operation(num) for num in numbers]

def square(x):
    return x ** 2

def cube(x):
    return x ** 3

numbers = [1, 2, 3, 4, 5]
squares = apply_operation(numbers, square)
cubes = apply_operation(numbers, cube)

print(f"平方: {squares}")
print(f"立方: {cubes}")

嵌套函数

python
def outer_function(x):
    """外部函数"""
    def inner_function(y):
        """内部函数"""
        return x + y
    return inner_function

# 创建闭包
add_five = outer_function(5)
result = add_five(3)
print(f"结果: {result}")  # 输出: 8

装饰器

python
def timing_decorator(func):
    """计时装饰器"""
    import time
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} 执行时间: {end_time - start_time:.4f}秒")
        return result
    return wrapper

@timing_decorator
def slow_function():
    """模拟耗时函数"""
    import time
    time.sleep(1)
    return "完成"

result = slow_function()

📦 模块和包

模块导入

python
# 导入整个模块
import math
print(f"π的值: {math.pi}")
print(f"平方根: {math.sqrt(16)}")

# 导入特定函数
from math import pi, sqrt
print(f"π的值: {pi}")
print(f"平方根: {sqrt(16)}")

# 导入并重命名
import math as m
print(f"π的值: {m.pi}")

# 导入所有(不推荐)
from math import *
print(f"π的值: {pi}")

创建自定义模块

创建模块文件 (math_utils.py)

python
# math_utils.py
"""数学工具模块"""

def add(a, b):
    """加法"""
    return a + b

def multiply(a, b):
    """乘法"""
    return a * b

def factorial(n):
    """计算阶乘"""
    if n <= 1:
        return 1
    return n * factorial(n - 1)

# 模块级别的变量
PI = 3.14159
E = 2.71828

# 只在直接运行时执行
if __name__ == "__main__":
    print("这是数学工具模块")
    print(f"5! = {factorial(5)}")

使用自定义模块

python
# 导入自定义模块
import math_utils

# 使用模块中的函数
result1 = math_utils.add(3, 5)
result2 = math_utils.multiply(4, 6)
result3 = math_utils.factorial(5)

print(f"加法: {result1}")
print(f"乘法: {result2}")
print(f"阶乘: {result3}")
print(f"π的值: {math_utils.PI}")

包的结构

my_package/
    __init__.py
    math_utils.py
    string_utils.py
    data_utils.py

init.py 文件

python
# __init__.py
"""我的工具包"""

from .math_utils import add, multiply, factorial
from .string_utils import reverse_string, count_words

__version__ = "1.0.0"
__author__ = "张三"

# 定义包的公共接口
__all__ = ['add', 'multiply', 'factorial', 'reverse_string', 'count_words']

🔍 内置函数

常用内置函数

python
# 数学函数
numbers = [1, 2, 3, 4, 5]
print(f"最大值: {max(numbers)}")
print(f"最小值: {min(numbers)}")
print(f"求和: {sum(numbers)}")
print(f"绝对值: {abs(-10)}")

# 类型转换
print(f"转整数: {int('123')}")
print(f"转浮点数: {float('3.14')}")
print(f"转字符串: {str(123)}")
print(f"转列表: {list('hello')}")

# 序列函数
print(f"长度: {len('hello')}")
print(f"排序: {sorted([3, 1, 4, 1, 5])}")
print(f"反转: {list(reversed([1, 2, 3]))}")

# 其他函数
print(f"范围: {list(range(5))}")
print(f"枚举: {list(enumerate(['a', 'b', 'c']))}")
print(f"压缩: {list(zip([1, 2, 3], ['a', 'b', 'c']))}")

lambda 函数

python
# 基本 lambda 函数
square = lambda x: x ** 2
print(f"平方: {square(5)}")

# 在列表中使用
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(f"平方列表: {squares}")

# 过滤
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"偶数: {even_numbers}")

# 排序
students = [('张三', 20), ('李四', 18), ('王五', 22)]
sorted_students = sorted(students, key=lambda x: x[1])
print(f"按年龄排序: {sorted_students}")

🎯 实践练习

练习1:计算器函数

编写一个计算器函数,支持加、减、乘、除四种运算,使用函数作为参数。

练习2:文本处理模块

创建一个文本处理模块,包含以下函数:

  • 统计字符数
  • 统计单词数
  • 反转字符串
  • 转换为标题格式

练习3:学生管理系统

编写一个学生管理系统的函数集合:

  • 添加学生
  • 删除学生
  • 查找学生
  • 显示所有学生

练习4:装饰器应用

编写一个装饰器,用于记录函数的调用次数和执行时间。

📚 函数文档和注释

文档字符串

python
def calculate_circle_area(radius):
    """
    计算圆的面积
    
    参数:
        radius (float): 圆的半径
        
    返回:
        float: 圆的面积
        
    异常:
        ValueError: 当半径小于0时抛出
        
    示例:
        >>> calculate_circle_area(5)
        78.53981633974483
    """
    if radius < 0:
        raise ValueError("半径不能为负数")
    return 3.14159 * radius ** 2

# 查看函数文档
print(calculate_circle_area.__doc__)

类型提示

python
from typing import List, Dict, Optional

def process_data(data: List[int], threshold: int = 10) -> Dict[str, int]:
    """
    处理数据列表
    
    参数:
        data: 整数列表
        threshold: 阈值,默认为10
        
    返回:
        包含统计信息的字典
    """
    result = {
        "总数": len(data),
        "大于阈值": len([x for x in data if x > threshold]),
        "平均值": sum(data) / len(data) if data else 0
    }
    return result

# 使用类型提示
numbers: List[int] = [1, 2, 3, 4, 5]
stats: Dict[str, int] = process_data(numbers)
print(f"统计结果: {stats}")

🔧 调试技巧

python
def debug_function(x, y):
    """调试函数示例"""
    print(f"调试: x = {x}, y = {y}")
    
    result = x + y
    print(f"调试: 计算结果 = {result}")
    
    return result

# 使用断言进行调试
def safe_divide(a, b):
    """安全除法"""
    assert b != 0, "除数不能为零"
    return a / b

# 使用 logging 模块
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

def logged_function(x):
    """带日志的函数"""
    logger.debug(f"函数开始执行,参数: {x}")
    result = x * 2
    logger.debug(f"函数执行完成,结果: {result}")
    return result

下一步

现在你已经掌握了 Python 的函数和模块,接下来应该学习:


💡 学习建议:多练习编写函数,理解模块化编程的思想