4Learning Python(第5版)

函数与模块

代码复用

def语句参数传递作用域lambda模块导入

🎯 AI 时代的学习建议:不要只读理论。理解这一章的设计动机(为什么需要这个概念?)和边界条件(什么情况下会失效?)。当 AI 生成的代码涉及这些概念时,你能判断它是否用对了场景。AI 能帮你总结内容,但无法替代你亲手阅读、思考、建立直觉的过程。

第4章:函数与模块(Functions and Modules)

一、导读

1.1 本章学习目标

第4章讲解 Python 的函数和模块系统。函数是代码复用的基础,模块是代码组织的核心。

1.2 为什么第四章如此重要

函数和模块是 Python 编程的基石。理解它们才能写出可复用、可维护的代码。

1.3 核心问题引导

Python 函数有哪些特性?

参数传递的机制是什么?

作用域规则是什么?

模块如何导入和使用?


二、核心概念详解

4.1 函数基础

python
# 基本函数
def greet(name):
    return f"Hello, {name}!"

# 默认参数
def power(base, exp=2):
    return base ** exp

# 关键字参数
def create_user(name, age, city="Unknown"):
    return {"name": name, "age": age, "city": city}

# 可变参数
def total(*args):
    return sum(args)

# 关键字可变参数
def config(**kwargs):
    return kwargs

# Lambda
square = lambda x: x ** 2

4.2 参数传递

python
# Python 使用"按对象引用传递"
def modify_list(lst):
    lst.append(4)  # 修改原对象

def reassign(x):
    x = [1, 2, 3]  # 重新绑定,不影响外部

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list)  # [1, 2, 3, 4]

my_var = [1, 2]
reassign(my_var)
print(my_var)  # [1, 2](未改变)

4.3 作用域

python
# LEGB 规则:Local → Enclosing → Global → Built-in

x = "global"

def outer():
    x = "enclosing"
    
    def inner():
        x = "local"
        print(x)  # "local"
    
    inner()
    print(x)  # "enclosing"

outer()
print(x)  # "global"

# global 和 nonlocal
def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
    return increment

4.4 模块

python
# 导入模块
import math
print(math.pi)

# 导入特定内容
from os.path import join, exists

# 别名
import numpy as np

# 导入所有(不推荐)
from module import *

# __name__ 和 __main__
if __name__ == "__main__":
    # 直接运行时执行
    main()

三、实战案例

4.1 装饰器

python
import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start
        print(f"{func.__name__} took {elapsed:.2f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "done"

slow_function()  # slow_function took 1.00s

四、本章小结

Python 函数支持默认参数、可变参数、关键字参数。参数按对象引用传递。LEGB 作用域规则。模块通过 import 导入。


五、思考与练习

Python 的参数传递机制是什么?

LEGB 作用域规则是什么?

装饰器如何工作?

模块和包有什么区别?

__name__ == "__main__" 的作用是什么?


4/8函数与模
0%