网站首页 > 技术文章 正文
6.1 函数基础
6.1.1 函数定义与调用
函数定义语法:
def function_name(parameters):
"""文档字符串(可选)"""
# 函数体
return [expression] # 可选
函数调用原理:
6.1.2 函数组成要素
表6-1 函数核心组成要素
要素 | 说明 | 示例 |
函数名 | 标识函数的名称 | calculate_area |
参数 | 函数接收的输入 | radius |
函数体 | 执行的代码块 | return 3.14 * radius**2 |
返回值 | 函数输出的结果 | 78.5 |
文档字符串 | 函数说明文档 | """计算圆面积""" |
6.1.3 简单函数示例
def greet(name):
"""返回个性化问候语
Args:
name (str): 用户名
Returns:
str: 问候字符串
"""
return f"Hello, {name.capitalize()}!"
# 调用示例
print(greet("alice")) # Hello, Alice!
6.2 参数传递
6.2.1 参数类型
四种参数类型:
参数组合顺序:
def func(positional, keyword=value, *args, **kwargs):
pass
6.2.2 参数传递示例
# 位置参数
def power(base, exponent):
return base ** exponent
# 关键字参数
print(power(exponent=3, base=2)) # 8
# 默认参数
def connect(host, port=3306, timeout=10):
print(f"连接到 {host}:{port}, 超时:{timeout}s")
# 可变位置参数(*args)
def sum_numbers(*numbers):
return sum(numbers)
# 可变关键字参数(**kwargs)
def build_profile(**info):
for key, value in info.items():
print(f"{key}: {value}")
6.2.3 参数解包
# 列表/元组解包为位置参数
args = [3, 4]
print(power(*args)) # 81
# 字典解包为关键字参数
kwargs = {"base": 2, "exponent": 5}
print(power(**kwargs)) # 32
6.3 返回值与作用域
6.3.1 返回值特性
多返回值实现:
def analyze_number(n):
return n**2, n**3, abs(n)
square, cube, absolute = analyze_number(-3)
返回函数:
def create_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
print(double(5)) # 10
6.3.2 变量作用域
LEGB规则:
作用域示例:
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # local
inner()
print(x) # enclosing
outer()
print(x) # global
6.4 高阶函数
6.4.1 常用高阶函数
map/filter/reduce:
numbers = [1, 2, 3, 4]
# map应用函数到每个元素
squares = list(map(lambda x: x**2, numbers))
# filter过滤元素
evens = list(filter(lambda x: x%2==0, numbers))
# reduce累积计算
from functools import reduce
product = reduce(lambda x,y: x*y, numbers)
6.4.2 函数作为参数
def apply_operation(func, a, b):
"""应用指定操作到两个数"""
return func(a, b)
result = apply_operation(lambda x,y: x+y, 3, 4) # 7
6.5 闭包与装饰器
6.5.1 闭包实现
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
print(c(), c(), c()) # 1 2 3
6.5.2 装饰器应用
简单装饰器:
def timer(func):
"""测量函数执行时间"""
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__}执行耗时: {end-start:.4f}s")
return result
return wrapper
@timer
def long_running_task(n):
return sum(i*i for i in range(n))
带参数装饰器:
def repeat(times):
"""重复执行函数"""
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
6.6 函数式编程工具
6.6.1 functools模块
from functools import partial, lru_cache
# 偏函数
square_root = partial(power, exponent=0.5)
print(square_root(9)) # 3.0
# 缓存装饰器
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
6.6.2 生成器函数
def fibonacci_sequence(limit):
"""生成斐波那契数列"""
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
print(list(fibonacci_sequence(100)))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
6.7 综合应用举例
案例1:数据管道处理
def data_pipeline():
"""数据处理管道示例"""
# 数据源
raw_data = ["10", "20", "30", "abc", "40"]
# 处理步骤
processed = (
map(str.strip, raw_data), # 去空格
filter(str.isdigit, _), # 过滤数字
map(int, _), # 转整数
map(lambda x: x*2, _), # 数值加倍
list # 转为列表
)
for step in processed:
print(f"当前步骤: {step.__name__ if hasattr(step, '__name__') else str(step)}")
data = step(data) if 'data' in locals() else step
print(f"处理结果: {data}")
return data
print("最终结果:", data_pipeline())
案例2:权限检查装饰器
def permission_required(permission):
"""权限检查装饰器"""
def decorator(func):
def wrapper(user, *args, **kwargs):
if user.get("permissions", 0) & permission != permission:
raise PermissionError("权限不足")
return func(user, *args, **kwargs)
return wrapper
return decorator
# 权限定义
READ = 0b001
WRITE = 0b010
ADMIN = 0b100
@permission_required(READ | WRITE)
def edit_document(user, document):
print(f"{user['name']}正在编辑{document}")
# 使用示例
user = {"name": "Alice", "permissions": 0b011}
try:
edit_document(user, "重要文件")
except PermissionError as e:
print(e)
6.8 学习路线图
6.9 学习总结
- 核心要点:
- 理解函数定义与调用机制
- 掌握各种参数传递方式
- 熟练使用装饰器模式
- 了解函数式编程思想
- 实践建议:
- 函数保持单一职责原则
- 合理使用默认参数提高可用性
- 为公共函数添加文档字符串
- 使用装饰器分离横切关注点
- 进阶方向:
- 协程与异步函数
- 函数签名检查(inspect模块)
- 描述符协议实现
- 元类编程
- 常见陷阱:
- 可变默认参数问题
- 闭包变量捕获时机
- 装饰器堆叠顺序
- 名称空间污染
持续更新Python编程学习日志与技巧,敬请关注!
猜你喜欢
- 2025-06-03 这3个高级Python函数,不能再被你忽略了
- 2025-06-03 python组合函数不允许你还不会的 10 个高效技巧
- 2025-06-03 Python内置函数range(python内置函数大全表)
- 2025-06-03 你不得不知道的10个最危险的Python函数
- 2025-06-03 告别重复,打造你的代码工具箱:Python函数深度解析
- 2025-06-03 python入门到脱坑 函数—函数的调用
- 2025-06-03 Python内置函数指南(python内置函数有哪些)
- 2025-06-03 PYTHON函数参数详解(python函数参数的类型)
- 2025-06-03 Python程序员都应该学习掌握的的25个最基本内置函数
- 2025-06-03 python为什么需要函数、类这些概念
- 263℃Python短文,Python中的嵌套条件语句(六)
- 262℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 256℃Python实现字符串小写转大写并写入文件
- 255℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 113℃原来2025是完美的平方年,一起探索六种平方的算吧
- 96℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 87℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)