函数是Python的核心掌握函数你就掌握了Python的半壁江山 前言在编程的世界里函数就像是一个神奇的加工厂——你往里面扔进原材料参数它经过一系列处理最终产出你想要的产品返回值。Python中的函数更是灵活多变既能简单如加法器又能复杂如装饰器工厂。本文将带你从零开始逐步深入Python函数的方方面面从基础的定义与调用到进阶的参数魔法再到高级的闭包与装饰器每个知识点都配有可直接运行的案例让你边学边练真正掌握函数编程的精髓。第一章 函数基础1.1 什么是函数函数是组织好的、可重复使用的、用来实现单一或相关联功能的代码段。打个比方你每天早晨要刷牙这个过程包括挤牙膏 → 刷牙 → 漱口。如果每次都要重复这3个步骤很麻烦。你把这些步骤打包成一个叫刷牙的动作函数以后每天只需要执行刷牙这个动作就行了里面的具体步骤不需要再关心。python# 没有函数的代码每次都要重复写 print(挤牙膏) print(刷牙) print(漱口) print(挤牙膏) print(刷牙) print(漱口) # ... 每次都要重复3行代码 # 有了函数只需定义一次随时调用 def brush_teeth(): 刷牙的完整流程 print(挤牙膏) print(刷牙) print(漱口) # 以后每天只需要调用一次函数即可 brush_teeth() # 超级方便函数的核心价值✅代码复用一次定义多次使用✅模块化将复杂功能拆分成小块便于管理✅易维护修改只需改一处所有调用自动更新✅可读性给代码块起个有意义的名称一看就懂1.2 函数的定义与调用定义函数使用def关键字调用函数使用函数名加括号。python# 定义函数的语法格式 def 函数名(参数列表): 函数的文档字符串说明函数的作用 函数体要执行的代码 return 返回值可选 # 示例1无参数无返回值的函数 def say_hello(): 打印问候语 print(Hello, Python!) # 调用函数 say_hello() # 输出: Hello, Python! # 示例2有参数有返回值的函数 def add(a, b): 计算两个数的和并返回 result a b return result # 调用函数并接收返回值 sum_result add(3, 5) print(f3 5 {sum_result}) # 输出: 3 5 8 # 示例3带默认参数的函数 def greet(name, greetingHello): 向指定的人打招呼 return f{greeting}, {name}! print(greet(Alice)) # 使用默认问候语: Hello, Alice! print(greet(Bob, Hi)) # 自定义问候语: Hi, Bob!1.3 函数的返回值returnreturn语句用于从函数中返回结果函数执行到return时会立即停止后续代码不再执行。python# 场景1返回单个值 def square(x): 计算平方 return x ** 2 print(square(5)) # 输出: 25 # 场景2返回多个值实际是返回元组 def get_min_max(numbers): 返回列表的最小值和最大值 return min(numbers), max(numbers) min_val, max_val get_min_max([3, 1, 7, 2, 9]) print(f最小值: {min_val}, 最大值: {max_val}) # 输出: 最小值: 1, 最大值: 9 # 场景3没有 return 语句 def print_hello(): print(Hello) result print_hello() # 先执行打印: Hello print(result) # 再打印返回值: None无返回值时默认返回 None # 场景4提前结束函数return 提前退出 def check_age(age): 检查年龄是否合法 if age 0: return 年龄不能为负数 # 返回错误信息并提前结束 if age 18: return 未成年 return 成年人 print(check_age(-5)) # 输出: 年龄不能为负数 print(check_age(16)) # 输出: 未成年 print(check_age(20)) # 输出: 成年人第二章 函数的参数详解2.1 位置参数位置参数是最基本的参数类型调用时参数的顺序和数量必须与定义时完全一致。python# 定义函数有3个位置参数 def introduce(name, age, city): print(f我叫{name}今年{age}岁来自{city}) # 调用时参数顺序必须匹配 introduce(张三, 25, 北京) # 正确 # introduce(张三, 北京, 25) # 错误顺序不对类型混乱2.2 默认参数默认参数在函数定义时就赋予了默认值调用时如果不传该参数则使用默认值。⚠️重要提醒默认参数必须放在位置参数之后python# 基本用法 def greet(name, greetingHello, punctuation!): return f{greeting}, {name}{punctuation} print(greet(Alice)) # Hello, Alice! print(greet(Bob, Hi)) # Hi, Bob! print(greet(Charlie, Hey, ~)) # Hey, Charlie~ # 常见坑默认参数使用可变对象 # ❌ 错误做法默认参数使用可变对象 def add_item(item, lst[]): # 默认参数是列表可变对象 lst.append(item) return lst print(add_item(1)) # [1] print(add_item(2)) # [1, 2] ← 这里出问题了期望是 [2]但实际结果受到上次调用的影响 # ✅ 正确做法使用 None 作为默认值 def add_item_correct(item, lstNone): if lst is None: lst [] lst.append(item) return lst print(add_item_correct(1)) # [1] print(add_item_correct(2)) # [2] ← 每次都重新创建列表符合预期2.3 关键字参数关键字参数让你在调用函数时指定参数名传值因此顺序可以打乱提高了代码可读性。pythondef introduce(name, age, city): print(f我叫{name}今年{age}岁来自{city}) # 位置参数方式调用必须按顺序 introduce(张三, 25, 北京) # 关键字参数方式调用可以打乱顺序 introduce(city上海, name李四, age30) # 混合使用位置参数在前关键字参数在后 introduce(王五, city广州, age28)2.4 可变参数*args 和 **kwargs当你不确定函数会接收多少个参数时可以使用可变参数。*args—— 接收任意数量的位置参数python# 场景计算任意多个数的和 def sum_numbers(*args): *args 会将所有传入的位置参数打包成一个元组(tuple) 例如sum_numbers(1,2,3,4) → args (1,2,3,4) total 0 for num in args: total num return total print(sum_numbers(1, 2, 3)) # 输出: 6 print(sum_numbers(10, 20, 30, 40)) # 输出: 100 print(sum_numbers()) # 输出: 0没有参数时 args 为空元组 # 场景打印任意数量学生的成绩 def print_scores(name, *scores): 第一个参数是姓名后面跟任意数量的成绩 print(f{name}的成绩: {scores}) print_scores(张三, 90, 85, 92) # 张三的成绩: (90, 85, 92) print_scores(李四, 88, 76) # 李四的成绩: (88, 76)**kwargs—— 接收任意数量的关键字参数pythondef show_info(**kwargs): **kwargs 会将所有传入的关键字参数打包成一个字典(dict) 例如show_info(name张三, age25) → kwargs {name:张三, age:25} for key, value in kwargs.items(): print(f{key}: {value}) show_info(name张三, age25, city北京) # 输出 # name: 张三 # age: 25 # city: 北京 show_info(product手机, price2999, stock100) # 输出 # product: 手机 # price: 2999 # stock: 100 # 综合使用 *args 和 **kwargs def wrapper_function(*args, **kwargs): *args 必须在 **kwargs 前面 print(位置参数:, args) print(关键字参数:, kwargs) wrapper_function(1, 2, 3, name张三, age25) # 输出 # 位置参数: (1, 2, 3) # 关键字参数: {name: 张三, age: 25}2.5 参数解包参数解包允许你将序列或字典解包后作为参数传递给函数。python# 使用 * 解包列表/元组对应位置参数 def add_three(a, b, c): return a b c nums [10, 20, 30] print(add_three(*nums)) # * 将列表解包为 10,20,30 → 输出: 60 # 使用 ** 解包字典对应关键字参数 def introduce(name, age, city): print(f我叫{name}今年{age}岁来自{city}) info {city: 北京, name: 张三, age: 25} introduce(**info) # ** 将字典解包为 name张三, age25, city北京 # 输出: 我叫张三今年25岁来自北京 # 使用 * 和 ** 混合解包 def complex_func(a, b, c, d, e): print(fa{a}, b{b}, c{c}, d{d}, e{e}) list_args [1, 2] dict_args {c: 3, d: 4, e: 5} complex_func(*list_args, **dict_args) # a1, b2, c3, d4, e5第三章 变量作用域3.1 局部变量与全局变量全局变量在函数外部定义的变量整个文件都可以访问局部变量在函数内部定义的变量只能在函数内部使用python# 全局变量 global_var 我是全局变量 def test(): # 局部变量 local_var 我是局部变量 print(global_var) # 可以访问全局变量 print(local_var) # 可以访问局部变量 test() print(global_var) # 可以正常访问在函数外 # print(local_var) # 会报错局部变量不能在函数外访问 # 全局变量的读取与修改 count 10 def read_global(): print(count) # 可以读取全局变量 def modify_global_bad(): count 20 # 这不是修改全局变量而是创建了一个新的局部变量 print(函数内部:, count) def modify_global_good(): global count # 声明 count 是全局变量 count 20 # 现在修改的是全局变量 print(函数内部:, count) read_global() # 输出: 10 modify_global_bad() # 输出: 函数内部: 20 print(外部:, count) # 输出: 外部: 10全局变量没有被修改 modify_global_good() # 输出: 函数内部: 20 print(外部:, count) # 输出: 外部: 20全局变量被修改了3.2 global 与 nonlocal 关键字global在函数内部声明使用全局变量nonlocal在嵌套函数中声明使用外层函数的变量python# global 示例 x 100 def outer_global_demo(): x 50 # 外层函数的局部变量 print(f外层函数中的 x: {x}) def inner(): global x # 声明使用全局变量 x x 200 # 修改的是全局变量 print(f内层函数中的 x: {x}) inner() print(f外层函数修改后的 x: {x}) # 外层 x 没有被修改仍是 50 outer_global_demo() print(f全局 x: {x}) # 全局 x 被修改为 200 # nonlocal 示例 def outer_nonlocal_demo(): y 10 # 外层函数的局部变量 print(f外层函数中的 y: {y}) def inner(): nonlocal y # 声明使用外层函数的 y y 20 # 修改的是外层函数的 y print(f内层函数中的 y: {y}) inner() print(f外层函数修改后的 y: {y}) # y 被修改为 20 outer_nonlocal_demo() # print(y) # 报错y 是 outer_nonlocal_demo 的局部变量不能在外部访问3.3 globals() 与 locals()globals()返回当前全局作用域中的所有变量字典形式locals()返回当前局部作用域中的所有变量字典形式python# 全局变量 name 张三 age 25 def scope_demo(): # 局部变量 city 北京 job 程序员 print( 局部作用域中的变量 ) print(locals()) # 查看当前函数内的局部变量 # 输出: {city: 北京, job: 程序员} print(\n 全局作用域中的变量 ) print(globals()) # 查看所有全局变量包含了很多内置变量 # 通过 globals() 动态访问和修改全局变量 print(f当前全局 name: {globals()[name]}) globals()[name] 李四 # 修改全局变量 print(f修改后全局 name: {globals()[name]}) scope_demo() print(f函数外部 name: {name}) # 输出: 李四第四章 高级函数4.1 匿名函数lambdalambda 函数是没有名字的简短函数通常用于一次性的简单操作。python# 基本语法 # lambda 参数: 表达式 # 普通函数写法 def add(x, y): return x y # lambda 写法 add_lambda lambda x, y: x y print(add_lambda(3, 5)) # 输出: 8 # 与内置函数结合使用 # 1. 与 sorted() 结合自定义排序规则 students [ {name: 张三, score: 85}, {name: 李四, score: 92}, {name: 王五, score: 78} ] # 按成绩升序排序 sorted_students sorted(students, keylambda stu: stu[score]) print(sorted_students) # 按成绩从低到高排列 # 2. 与 filter() 结合过滤数据 numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers list(filter(lambda x: x % 2 0, numbers)) print(even_numbers) # 输出: [2, 4, 6, 8, 10] # 3. 与 map() 结合批量处理数据 scores [60, 75, 88, 92, 55] # 将所有成绩加 5 分 new_scores list(map(lambda x: x 5, scores)) print(new_scores) # 输出: [65, 80, 93, 97, 60] # lambda 与条件表达式 # 取最大值 max_func lambda a, b: a if a b else b print(max_func(10, 20)) # 输出: 204.2 高阶函数高阶函数是指接收函数作为参数或返回一个函数的函数。python# 1. 接收函数作为参数 def apply_operation(func, x, y): 对 x 和 y 执行传入的操作函数 return func(x, y) def add(a, b): return a b def multiply(a, b): return a * b print(apply_operation(add, 10, 5)) # 输出: 15 print(apply_operation(multiply, 10, 5)) # 输出: 50 print(apply_operation(lambda a, b: a - b, 10, 5)) # 输出: 5 # 2. 返回一个函数 def get_operation(symbol): 根据符号返回对应的运算函数 if symbol : return lambda a, b: a b elif symbol -: return lambda a, b: a - b elif symbol *: return lambda a, b: a * b elif symbol /: return lambda a, b: a / b else: return lambda a, b: 不支持的运算符 # 获取加法函数并调用 add_func get_operation() print(add_func(10, 5)) # 输出: 15 # 获取减法函数并调用 sub_func get_operation(-) print(sub_func(10, 5)) # 输出: 5 # Python 内置高阶函数 # map()对序列中的每个元素应用函数 nums [1, 2, 3, 4, 5] squared list(map(lambda x: x ** 2, nums)) print(squared) # 输出: [1, 4, 9, 16, 25] # filter()过滤序列中的元素 numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers list(filter(lambda x: x % 2 1, numbers)) print(odd_numbers) # 输出: [1, 3, 5, 7, 9] # reduce()对序列进行累积计算 from functools import reduce nums [1, 2, 3, 4, 5] product reduce(lambda a, b: a * b, nums) print(product) # 输出: 1201*2*3*4*54.3 递归函数递归函数是自己调用自己的函数适合解决可以拆分成相似子问题的场景。python# 必备条件 # 1. 基线条件停止条件什么时候停止递归 # 2. 递归条件推进条件调用自身向基线条件靠近 # 案例1计算阶乘 n! def factorial(n): 计算 n 的阶乘 # 基线条件0! 1, 1! 1 if n 1: return 1 # 递归条件n! n * (n-1)! return n * factorial(n - 1) print(factorial(5)) # 输出: 120 print(factorial(10)) # 输出: 3628800 # 执行过程解析 # factorial(5) 5 * factorial(4) # 5 * 4 * factorial(3) # 5 * 4 * 3 * factorial(2) # 5 * 4 * 3 * 2 * factorial(1) # 5 * 4 * 3 * 2 * 1 # 120 # 案例2斐波那契数列 def fibonacci(n): 返回斐波那契数列的第 n 项从0开始 斐波那契数列0, 1, 1, 2, 3, 5, 8, 13, 21, ... # 基线条件 if n 0: return 0 elif n 1: return 1 # 递归条件f(n) f(n-1) f(n-2) return fibonacci(n - 1) fibonacci(n - 2) print(fibonacci(0)) # 输出: 0 print(fibonacci(1)) # 输出: 1 print(fibonacci(2)) # 输出: 1 print(fibonacci(3)) # 输出: 2 print(fibonacci(4)) # 输出: 3 print(fibonacci(10)) # 输出: 55 # 案例3计算文件夹大小实际应用 import os def get_folder_size(folder_path): 递归计算文件夹的总大小实际开发中非常有用 total_size 0 try: for item in os.listdir(folder_path): item_path os.path.join(folder_path, item) if os.path.isfile(item_path): total_size os.path.getsize(item_path) elif os.path.isdir(item_path): total_size get_folder_size(item_path) # 递归调用 except PermissionError: print(f无权限访问: {folder_path}) return total_size # 注意不要直接运行下面这行否则会扫描整个目录 # print(f当前目录大小: {get_folder_size(.)} 字节) # 递归的注意事项 # 1. 递归深度限制Python 默认递归深度为 1000 # 2. 性能问题递归可能带来较大开销大深度时考虑改用循环 # 3. 必须要有基线条件否则会无限递归导致栈溢出 # 查看递归限制 import sys print(f默认递归限制: {sys.getrecursionlimit()}) # 可以通过 sys.setrecursionlimit(2000) 设置更高的限制慎用第五章 闭包与装饰器5.1 闭包Closure闭包是指在一个内部函数中引用了外部函数的变量并且这个内部函数被返回了。简单理解函数 它捕获的外部变量 闭包python# 闭包的基本形式 def outer_function(x): 外部函数 # 外部函数的局部变量 message f捕获的变量 x {x} def inner_function(y): 内部函数闭包 # 内部函数使用了外部函数的变量 x 和 message return f{message}, 传入的参数 y {y} # 返回内部函数 return inner_function # 创建闭包 closure outer_function(10) # 调用闭包 print(closure(5)) # 输出: 捕获的变量 x 10, 传入的参数 y 5 # 即使外部函数已经执行完毕闭包仍然持有外部变量的值 # 这就是闭包的记忆功能 # 案例1简单的计数器 def create_counter(): 创建一个计数器闭包 count 0 # 外部变量 def counter(): nonlocal count # 声明使用外部函数的变量 count 1 return count return counter # 创建两个独立的计数器 counter1 create_counter() counter2 create_counter() print(counter1()) # 输出: 1 print(counter1()) # 输出: 2 print(counter1()) # 输出: 3 print(counter2()) # 输出: 1独立的计数器从1开始 print(counter2()) # 输出: 2 # 案例2带初始值的计数器 def create_counter_with_start(start0): 创建从指定值开始的计数器 count start def counter(): nonlocal count count 1 return count return counter counter_from_10 create_counter_with_start(10) print(counter_from_10()) # 输出: 11 print(counter_from_10()) # 输出: 12 # 案例3缓存计算结果提高性能 def make_cache(): 创建一个缓存闭包用于存储计算结果 cache {} def cached_function(key, value): if key not in cache: print(f计算并缓存 key{key}) cache[key] value else: print(f从缓存读取 key{key}) return cache[key] return cached_function cache make_cache() print(cache(a, 1)) # 输出: 计算并缓存 keya \n 1 print(cache(a, 2)) # 输出: 从缓存读取 keya \n 1实际参数2被忽略了 print(cache(b, 3)) # 输出: 计算并缓存 keyb \n 35.2 装饰器Decorator装饰器本质上是一个函数它接收一个函数作为参数返回一个新的函数在不修改原函数代码的情况下增强其功能。python# 装饰器基础无参数版本 def my_decorator(func): 最简单的装饰器 def wrapper(): print(在函数执行前...) func() # 执行原函数 print(在函数执行后...) return wrapper my_decorator # 语法糖等价于 say_hello my_decorator(say_hello) def say_hello(): print(Hello, World!) say_hello() # 输出 # 在函数执行前... # Hello, World! # 在函数执行后... # 装饰器处理带参数的函数 def log_decorator(func): 记录函数调用日志的装饰器 def wrapper(*args, **kwargs): print(f正在调用函数: {func.__name__}) print(f参数: args{args}, kwargs{kwargs}) result func(*args, **kwargs) print(f返回值: {result}) return result return wrapper log_decorator def add(a, b): return a b add(3, 5) # 输出 # 正在调用函数: add # 参数: args(3, 5), kwargs{} # 返回值: 8 # 带参数的装饰器装饰器工厂 def repeat(times): 装饰器工厂指定函数重复执行的次数 def decorator(func): def wrapper(*args, **kwargs): for i in range(times): print(f第 {i1} 次执行:) result func(*args, **kwargs) return result return wrapper return decorator repeat(3) # 等价于 say_hello repeat(3)(say_hello) def say_hello(): print(Hello!) say_hello() # 输出 # 第 1 次执行: # Hello! # 第 2 次执行: # Hello! # 第 3 次执行: # Hello! # 多个装饰器叠加 # 装饰器的执行顺序从下到上先装饰最靠近函数的那个 def decorator_A(func): def wrapper(): print(A-执行前) func() print(A-执行后) return wrapper def decorator_B(func): def wrapper(): print(B-执行前) func() print(B-执行后) return wrapper decorator_A decorator_B # 先执行这个靠近函数 def my_func(): print(原函数执行) my_func() # 输出 # A-执行前 # B-执行前 # 原函数执行 # B-执行后 # A-执行后5.3 装饰器常用案例 案例1计时器装饰器性能分析pythonimport time def timer_decorator(func): 计算函数执行时间的装饰器 def wrapper(*args, **kwargs): start_time time.time() result func(*args, **kwargs) end_time time.time() elapsed end_time - start_time print(f函数 {func.__name__} 执行耗时: {elapsed:.4f} 秒) return result return wrapper timer_decorator def slow_function(): 模拟一个耗时操作 time.sleep(1.2) print(耗时操作完成) return 100 result slow_function() # 输出 # 耗时操作完成 # 函数 slow_function 执行耗时: 1.2001 秒 案例2权限校验装饰器python# 模拟用户权限 USER_PERMISSIONS { admin: [read, write, delete], user: [read], guest: [] } def require_permission(permission): 权限校验装饰器工厂 def decorator(func): def wrapper(username, *args, **kwargs): # 获取用户的权限列表 permissions USER_PERMISSIONS.get(username, []) if permission in permissions: print(f✅ {username} 拥有 {permission} 权限) return func(username, *args, **kwargs) else: print(f❌ {username} 没有 {permission} 权限操作被拒绝) return None return wrapper return decorator require_permission(delete) def delete_file(username, filename): return f{username} 删除了文件: {filename} # 测试不同用户 print(delete_file(admin, data.txt)) # ✅ 拥有权限 print(delete_file(user, data.txt)) # ❌ 没有权限 print(delete_file(guest, data.txt)) # ❌ 没有权限 案例3日志记录装饰器pythonimport logging from datetime import datetime # 配置日志 logging.basicConfig( levellogging.INFO, format%(asctime)s - %(name)s - %(levelname)s - %(message)s, handlers[ logging.FileHandler(app.log, encodingutf-8), logging.StreamHandler() ] ) logger logging.getLogger(__name__) def log_decorator(func): 记录函数调用的日志装饰器 def wrapper(*args, **kwargs): # 记录开始 logger.info(f开始执行: {func.__name__}) logger.info(f参数: args{args}, kwargs{kwargs}) try: # 执行原函数 result func(*args, **kwargs) logger.info(f执行成功: {func.__name__}, 返回值: {result}) return result except Exception as e: logger.error(f执行失败: {func.__name__}, 错误: {e}) raise return wrapper log_decorator def divide(a, b): return a / b # 测试 divide(10, 2) # 正常执行 # divide(10, 0) # 会触发除零错误并记录日志取消注释测试 案例4重试装饰器网络请求常用pythonimport time import random def retry(max_retries3, delay1): 重试装饰器当函数执行失败时自动重试 :param max_retries: 最大重试次数 :param delay: 每次重试间隔秒 def decorator(func): def wrapper(*args, **kwargs): for attempt in range(max_retries): try: print(f尝试 {attempt 1}/{max_retries}) result func(*args, **kwargs) print(成功执行) return result except Exception as e: print(f失败: {e}) if attempt max_retries - 1: print(f等待 {delay} 秒后重试...) time.sleep(delay) else: print(所有重试均失败) raise return None return wrapper return decorator retry(max_retries3, delay0.5) def unstable_function(): 模拟一个可能失败的函数随机成功 if random.random() 0.7: # 70% 概率失败 raise ValueError(随机失败) return 成功 print(unstable_function()) 案例5缓存装饰器functools.lru_cache 原理实现pythondef memoize(func): 手动实现缓存装饰器类似 functools.lru_cache 将函数的计算结果缓存起来避免重复计算 cache {} def wrapper(*args): # 将参数转换为可哈希的元组 key args if key in cache: print(f从缓存读取: {args}) return cache[key] else: print(f计算并缓存: {args}) result func(*args) cache[key] result return result return wrapper memoize def fibonacci(n): 使用缓存的斐波那契数列计算效率大幅提升 if n 2: return n return fibonacci(n - 1) fibonacci(n - 2) print(fibonacci(10)) # 会计算并缓存所有子问题 print(fibonacci(10)) # 直接从缓存读取 print(fibonacci(8)) # 从缓存读取之前已经计算过 案例6类型检查装饰器pythondef type_check(expected_types): 类型检查装饰器验证函数参数的类型是否符合预期 expected_types: 参数类型元组如 (int, str) def decorator(func): def wrapper(*args, **kwargs): # 检查位置参数的类型 for i, (arg, expected_type) in enumerate(zip(args, expected_types)): if not isinstance(arg, expected_type): raise TypeError( f参数 {i} 类型错误: 期望 {expected_type.__name__}, f实际 {type(arg).__name__} ) return func(*args, **kwargs) return wrapper return decorator type_check((int, int)) def add_numbers(a, b): return a b print(add_numbers(3, 5)) # 正常输出 8 # print(add_numbers(3, 5)) # 报错类型不匹配取消注释测试 总结本文从基础到高级系统性地讲解了 Python 函数的各个核心知识点章节核心内容关键知识点第一章函数基础定义、调用、参数、返回值第二章参数详解位置参数、默认参数、关键字参数、*args、**kwargs、参数解包第三章变量作用域局部/全局变量、global、nonlocal、globals()、locals()第四章高级函数lambda、高阶函数、递归第五章闭包与装饰器闭包原理、装饰器实现、6个实战案例掌握函数你就掌握了 Python 编程的核心能力上面的每个案例都可以直接运行建议你动手敲一遍加深理解。作者后记写作不易如果这篇文章对你有帮助欢迎点赞、收藏、转发你的支持是我继续创作的动力 如有疑问或建议欢迎在评论区留言交流。