1. 函数的基本概念解析
函数是编程语言中最基础也最重要的构建块之一。就像建筑工地上的砖块,函数是构建复杂程序的原材料。我第一次真正理解函数的重要性是在写一个简单的计算器程序时——当我把加减乘除的操作封装成函数后,代码突然变得清晰易读多了。
函数本质上是一个可重复使用的代码块,它接收输入(参数),执行特定任务,然后返回输出(结果)。这种封装带来的好处是显而易见的:避免重复代码、提高可读性、便于维护。想象一下,如果你每次要做加法都得重新写一遍加法逻辑,那代码会变得多么冗长混乱。
2. 函数的组成部分详解
2.1 函数声明与定义
在大多数编程语言中,函数声明通常包含几个关键部分。以Python为例:
python复制def calculate_area(width, height):
"""计算矩形面积"""
area = width * height
return area
这里def是定义函数的关键字,calculate_area是函数名,括号内的width和height是参数,冒号后面的缩进块是函数体,return语句返回计算结果。
注意:函数命名应该清晰表达其功能,使用动词+名词的形式是个好习惯,比如
get_user_info比user更明确。
2.2 参数传递机制
参数传递看似简单,但实际使用时容易踩坑。主要有两种传递方式:
- 值传递:函数内对参数的修改不会影响原始值
- 引用传递:函数内对参数的修改会影响原始对象
在Python中,基本数据类型(int, float等)是值传递,而列表、字典等是引用传递。我曾经因为不理解这个区别,调试了整整一个下午:
python复制def modify_list(my_list):
my_list.append(4) # 会影响原始列表
def modify_number(num):
num += 1 # 不会影响原始数值
2.3 返回值处理
函数可以返回任何类型的值,也可以返回多个值(实际上是返回元组)。没有return语句的函数实际上返回None。
一个常见错误是忽略返回值:
python复制result = calculate_area(5, 3)
print("面积是:", result) # 正确使用返回值
3. 函数的进阶特性
3.1 作用域与生命周期
理解变量的作用域对编写可靠函数至关重要。函数内部定义的变量是局部变量,只在函数内有效;函数外定义的是全局变量。
python复制global_var = "全局"
def scope_demo():
local_var = "局部"
print(global_var) # 可以访问全局变量
print(local_var) # 可以访问局部变量
scope_demo()
print(local_var) # 这里会报错,因为local_var不存在
提示:尽量避免在函数内修改全局变量,这会导致代码难以理解和维护。如果必须使用,明确用
global关键字声明。
3.2 默认参数与可变参数
函数参数可以设置默认值,使调用更灵活:
python复制def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
可变参数允许函数接受任意数量的参数:
python复制def sum_all(*numbers):
return sum(numbers)
3.3 匿名函数(lambda)
对于简单操作,可以使用匿名函数:
python复制square = lambda x: x * x
虽然简洁,但过度使用会降低代码可读性。我建议只在作为其他函数的参数时使用lambda,比如:
python复制sorted_list = sorted(my_list, key=lambda x: x[1])
4. 函数的最佳实践
4.1 单一职责原则
好的函数应该只做一件事,并且做好这件事。如果一个函数超过20行,或者做了多件不相关的事,就该考虑拆分了。
我曾经写过一个处理用户数据的函数,它同时验证输入、转换格式、计算统计量和生成报告——后来维护时简直是一场噩梦。拆分成四个小函数后,每个都变得简单明了。
4.2 文档字符串(Docstring)
为函数添加清晰的文档说明是个好习惯:
python复制def calculate_tax(income):
"""
计算应缴税款
参数:
income (float): 年收入
返回:
float: 应缴税款金额
"""
# 计算逻辑...
这样其他开发者(包括未来的你)能快速理解函数用途。
4.3 错误处理
健壮的函数应该能处理异常情况:
python复制def divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("错误:除数不能为零")
return None
5. 常见问题与调试技巧
5.1 参数传递错误
最常见的错误之一是参数顺序不对:
python复制def create_user(name, age, email):
# ...
create_user("user@example.com", "Alice", 30) # 参数顺序错了!
解决方法:使用关键字参数调用:
python复制create_user(email="user@example.com", name="Alice", age=30)
5.2 修改可变默认参数
这是一个经典陷阱:
python复制def add_item(item, items=[]):
items.append(item)
return items
多次调用这个函数会发现items在不断累积,因为默认参数在函数定义时就被创建了。正确做法:
python复制def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
5.3 递归深度限制
递归函数简洁但容易达到最大递归深度。比如计算阶乘:
python复制def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
对于大数会报错。可以考虑用循环实现,或者使用尾递归优化(如果语言支持)。
6. 函数在实际项目中的应用
6.1 模块化开发
在真实项目中,函数帮助我们实现模块化。比如一个电商系统可能有:
python复制def calculate_total(cart_items):
# 计算购物车总价
def process_payment(user, amount):
# 处理支付
def send_confirmation_email(user, order_details):
# 发送确认邮件
每个函数处理一个明确的任务,组合起来完成复杂业务逻辑。
6.2 高阶函数应用
高阶函数(接收函数作为参数的函数)提供了强大的抽象能力。比如:
python复制def apply_operation(data, operation):
return [operation(x) for x in data]
numbers = [1, 2, 3]
squared = apply_operation(numbers, lambda x: x**2)
6.3 装饰器模式
装饰器是Python中基于函数的强大特性:
python复制def log_time(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} 执行时间: {time.time()-start:.2f}s")
return result
return wrapper
@log_time
def complex_calculation():
# 耗时计算
...
7. 性能考量与优化
7.1 函数调用开销
虽然现代解释器对函数调用做了很多优化,但在性能关键路径上,过多的函数调用仍会影响性能。我曾经优化过一个数值计算密集的代码,通过内联一些简单函数获得了20%的速度提升。
7.2 记忆化(Memoization)
对于计算昂贵的纯函数,可以使用记忆化缓存结果:
python复制from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
7.3 选择合适的数据结构
函数内部使用的数据结构会极大影响性能。比如频繁检查元素是否存在时,使用集合(set)比列表(list)更高效。
8. 测试与调试技巧
8.1 单元测试
为重要函数编写单元测试:
python复制import unittest
class TestMathFunctions(unittest.TestCase):
def test_calculate_area(self):
self.assertEqual(calculate_area(3, 4), 12)
self.assertEqual(calculate_area(0, 10), 0)
8.2 调试复杂函数
当函数行为不符合预期时:
- 检查输入参数是否正确
- 添加打印语句或使用调试器逐步执行
- 验证边界条件(空输入、极值等)
- 检查返回值是否符合预期
8.3 性能分析
使用profiler找出性能瓶颈:
python复制import cProfile
cProfile.run('complex_calculation()')
9. 不同语言中的函数特性
虽然函数的基本概念相通,但不同语言有各自的特点:
9.1 JavaScript的函数
JavaScript函数是一等公民,可以赋值给变量:
javascript复制const greet = function(name) {
console.log(`Hello, ${name}`);
}
还有箭头函数:
javascript复制const square = x => x * x;
9.2 Java的方法
Java中函数必须属于某个类:
java复制public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
9.3 Go的函数
Go支持多返回值:
go复制func divide(a, b float64) (float64, error) {
if b == 0.0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
10. 函数式编程范式
函数式编程强调纯函数(无副作用)和不可变数据:
10.1 纯函数的特点
- 相同输入总是产生相同输出
- 没有副作用(不修改外部状态)
- 不依赖外部状态
10.2 高阶函数应用
python复制from functools import reduce
numbers = [1, 2, 3, 4]
sum = reduce(lambda x, y: x + y, numbers)
10.3 不可变数据结构
使用元组代替列表,创建新对象而非修改现有对象:
python复制def add_element(immutable_tuple, element):
return immutable_tuple + (element,)
11. 设计模式中的函数应用
许多设计模式都依赖函数的高级用法:
11.1 策略模式
使用函数作为可互换的算法:
python复制def bubble_sort(data):
# 冒泡排序实现
...
def quick_sort(data):
# 快速排序实现
...
def sort_data(data, strategy=quick_sort):
return strategy(data)
11.2 工厂模式
函数可以作为工厂创建对象:
python复制def create_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
else:
raise ValueError("未知动物类型")
11.3 观察者模式
使用回调函数实现事件通知:
python复制class Button:
def __init__(self):
self.click_handlers = []
def on_click(self, handler):
self.click_handlers.append(handler)
def click(self):
for handler in self.click_handlers:
handler()
12. 现代编程中的函数趋势
12.1 异步函数
处理I/O密集型任务:
python复制import asyncio
async def fetch_data(url):
# 模拟网络请求
await asyncio.sleep(1)
return f"数据来自 {url}"
12.2 类型提示
提高代码可维护性:
python复制from typing import List
def process_items(items: List[str]) -> int:
return len(items)
12.3 函数组合
将简单函数组合成复杂操作:
python复制from toolz import compose
clean = str.strip
capitalize = str.capitalize
format_name = compose(capitalize, clean)
formatted = format_name(" john ") # "John"
13. 函数在算法中的应用
13.1 分治算法
函数自然适合实现分治策略:
python复制def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
13.2 回溯算法
递归函数实现回溯:
python复制def solve_sudoku(board):
empty = find_empty_cell(board)
if not empty:
return True # 解完了
row, col = empty
for num in range(1, 10):
if is_valid(board, num, (row, col)):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0 # 回溯
return False
13.3 动态规划
函数记忆化是动态规划的基础:
python复制@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
14. 函数与面向对象编程
14.1 方法与函数的区别
方法是绑定到对象的函数:
python复制class Calculator:
def add(self, a, b): # 这是一个方法
return a + b
def add(a, b): # 这是一个独立函数
return a + b
14.2 静态方法与类方法
python复制class MyClass:
@staticmethod
def static_method():
print("静态方法")
@classmethod
def class_method(cls):
print(f"类方法,访问类 {cls}")
14.3 魔法方法
Python用特殊命名的方法实现运算符重载:
python复制class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
15. 函数式API设计
15.1 流畅接口
通过返回self实现方法链:
python复制class QueryBuilder:
def select(self, columns):
self.columns = columns
return self
def where(self, condition):
self.condition = condition
return self
def execute(self):
# 构建并执行查询
...
builder = QueryBuilder()
result = builder.select("name, age").where("age > 18").execute()
15.2 柯里化
将多参数函数转换为一系列单参数函数:
python复制from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
15.3 管道操作
将多个函数串联起来:
python复制from toolz import pipe
result = pipe(
" hello world ",
str.strip,
str.title,
lambda s: s.replace(" ", "_")
) # "Hello_World"
16. 函数性能优化进阶
16.1 内联函数
对于简单函数,内联可能提高性能:
python复制# 原始代码
def square(x):
return x * x
result = square(5)
# 优化后
result = 5 * 5
16.2 使用内置函数
内置函数通常是用C实现的,速度更快:
python复制# 较慢
total = 0
for num in numbers:
total += num
# 更快
total = sum(numbers)
16.3 避免不必要的函数调用
在循环内部减少函数调用:
python复制# 不理想
for item in large_list:
processed = expensive_function(item)
...
# 更好
process = expensive_function # 缓存函数引用
for item in large_list:
processed = process(item)
...
17. 函数安全注意事项
17.1 输入验证
永远不要信任函数输入:
python复制def divide(a: float, b: float) -> float:
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("参数必须是数字")
if b == 0:
raise ValueError("除数不能为零")
return a / b
17.2 避免全局状态
依赖全局状态的函数难以测试和维护:
python复制# 不推荐
config = {}
def update_settings(new_settings):
global config
config.update(new_settings)
# 更好
def update_settings(config, new_settings):
return {**config, **new_settings}
17.3 资源清理
确保资源被正确释放:
python复制def process_file(path):
try:
with open(path) as f:
return f.read()
except IOError as e:
print(f"无法读取文件: {e}")
raise
18. 函数文档与协作
18.1 类型注解
Python的类型提示:
python复制from typing import Optional, List
def find_index(items: List[str], target: str) -> Optional[int]:
"""在列表中查找目标字符串的索引"""
for i, item in enumerate(items):
if item == target:
return i
return None
18.2 示例代码
在文档中包含使用示例:
python复制def format_name(first: str, last: str) -> str:
"""
格式化全名
示例:
>>> format_name("John", "Doe")
'Doe, John'
"""
return f"{last}, {first}"
18.3 API文档生成
使用工具自动生成文档:
python复制def calculate_tax(income: float, rate: float = 0.15) -> float:
"""
计算所得税
参数:
income: 年收入金额
rate: 税率,默认为15%
返回:
应缴税款金额
"""
return income * rate
这样的文档可以用Sphinx等工具自动生成API文档。
19. 函数调试高级技巧
19.1 装饰器调试
创建调试装饰器:
python复制def debug(func):
def wrapper(*args, **kwargs):
print(f"调用 {func.__name__},参数: {args}, {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} 返回: {result}")
return result
return wrapper
@debug
def add(a, b):
return a + b
19.2 交互式调试
在函数中嵌入调试点:
python复制def complex_function():
# ...一些代码...
breakpoint() # Python 3.7+
# ...更多代码...
19.3 日志记录
添加详细日志:
python复制import logging
logging.basicConfig(level=logging.DEBUG)
def process_data(data):
logging.debug(f"开始处理数据,长度: {len(data)}")
try:
result = do_complex_processing(data)
logging.info(f"成功处理数据,结果: {result}")
return result
except Exception as e:
logging.error(f"处理数据时出错: {str(e)}")
raise
20. 函数测试策略
20.1 单元测试
为每个函数编写测试:
python复制import unittest
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
def test_divide(self):
self.assertAlmostEqual(divide(1, 3), 0.333, places=3)
with self.assertRaises(ValueError):
divide(1, 0)
20.2 属性测试
使用假设测试验证函数属性:
python复制from hypothesis import given
import hypothesis.strategies as st
@given(st.integers(), st.integers())
def test_add_commutative(a, b):
assert add(a, b) == add(b, a)
20.3 性能测试
确保函数满足性能要求:
python复制import timeit
def test_performance():
time = timeit.timeit("add(1, 2)", setup="from __main__ import add", number=100000)
assert time < 0.1 # 10万次调用应小于0.1秒
21. 函数重构技巧
21.1 提取函数
将长函数拆分为小函数:
python复制# 重构前
def process_order(order):
# 验证订单
if not order.items:
raise ValueError("订单无商品")
if order.total <= 0:
raise ValueError("订单金额无效")
# 计算折扣
if order.customer.is_vip:
discount = 0.2
else:
discount = 0
# 应用折扣
order.total *= (1 - discount)
# 保存订单
db.save(order)
# 重构后
def validate_order(order):
if not order.items:
raise ValueError("订单无商品")
if order.total <= 0:
raise ValueError("订单金额无效")
def calculate_discount(customer):
return 0.2 if customer.is_vip else 0
def process_order(order):
validate_order(order)
discount = calculate_discount(order.customer)
apply_discount(order, discount)
save_order(order)
21.2 合并相似函数
消除重复代码:
python复制# 重构前
def calculate_area_rect(width, height):
return width * height
def calculate_area_square(side):
return side * side
# 重构后
def calculate_area(width, height=None):
if height is None:
height = width
return width * height
21.3 参数对象
将多个相关参数组合为对象:
python复制# 重构前
def create_user(name, email, age, address, phone):
...
# 重构后
class UserInfo:
def __init__(self, name, email, age, address, phone):
self.name = name
self.email = email
self.age = age
self.address = address
self.phone = phone
def create_user(user_info):
...
22. 函数与并发编程
22.1 线程安全函数
确保函数在多线程环境下安全:
python复制from threading import Lock
counter = 0
counter_lock = Lock()
def increment():
global counter
with counter_lock:
counter += 1
22.2 协程与异步函数
使用async/await编写异步代码:
python复制import asyncio
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
22.3 并行处理
利用多核CPU:
python复制from multiprocessing import Pool
def process_item(item):
# 处理单个项目
...
with Pool(4) as p: # 使用4个进程
results = p.map(process_item, items)
23. 函数设计模式
23.1 回调模式
将函数作为回调传递:
python复制def long_running_task(callback):
result = do_something()
callback(result)
def on_complete(result):
print("任务完成,结果:", result)
long_running_task(on_complete)
23.2 中间件模式
函数管道处理数据:
python复制def middleware_one(data, next_middleware):
print("中间件1处理前")
result = next_middleware(data)
print("中间件1处理后")
return result
def middleware_two(data, next_middleware):
print("中间件2处理前")
result = next_middleware(data)
print("中间件2处理后")
return result
def final_handler(data):
print("最终处理:", data)
return data.upper()
# 组合中间件
def apply_middleware(data):
return middleware_one(data, lambda d: middleware_two(d, final_handler))
23.3 策略模式
运行时选择算法:
python复制def bubble_sort(data):
# 实现冒泡排序
...
def quick_sort(data):
# 实现快速排序
...
def sort_data(data, strategy=quick_sort):
return strategy(data)
# 根据数据大小选择策略
def smart_sort(data):
if len(data) < 100:
return bubble_sort(data)
return quick_sort(data)
24. 函数与元编程
24.1 动态创建函数
在运行时生成函数:
python复制def create_adder(n):
def adder(x):
return x + n
return adder
add5 = create_adder(5)
print(add5(3)) # 8
24.2 函数内省
检查函数属性:
python复制def example(a, b=1):
"""示例函数"""
return a + b
print(example.__name__) # "example"
print(example.__doc__) # "示例函数"
print(example.__defaults__) # (1,)
24.3 装饰器工厂
创建参数化装饰器:
python复制def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello() # 打印3次Hello!
25. 函数与数据结构
25.1 高阶数据结构操作
使用函数处理复杂数据结���:
python复制users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30}
]
# 获取所有用户名
names = list(map(lambda user: user["name"], users))
# 过滤成年用户
adults = list(filter(lambda user: user["age"] >= 18, users))
25.2 自定义排序
使用函数作为排序键:
python复制students = [
{"name": "Alice", "grade": "B"},
{"name": "Bob", "grade": "A"},
{"name": "Charlie", "grade": "C"}
]
# 按成绩排序
sorted_students = sorted(students, key=lambda s: s["grade"])
25.3 树遍历
递归函数处理树结构:
python复制class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def traverse(node):
if node is None:
return
print(node.value)
traverse(node.left)
traverse(node.right)
26. 函数与领域特定语言(DSL)
26.1 流畅接口
创建可读的API:
python复制class Query:
def __init__(self):
self._select = "*"
self._where = []
def select(self, columns):
self._select = columns
return self
def where(self, condition):
self._where.append(condition)
return self
def build(self):
where = " AND ".join(self._where) if self._where else "1=1"
return f"SELECT {self._select} FROM table WHERE {where}"
query = Query().select("name, age").where("age > 18").where("status = 'active'").build()
26.2 表达式构建
使用函数构建复杂表达式:
python复制class Expr:
def __add__(self, other):
return Add(self, other)
def __eq__(self, other):
return Equal(self, other)
class Column(Expr):
def __init__(self, name):
self.name = name
class Add(Expr):
def __init__(self, left, right):
self.left = left
self.right = right
class Equal(Expr):
def __init__(self, left, right):
self.left = left
self.right = right
# 使用示例
age = Column("age")
condition = (age + 1) == 30
26.3 规则引擎
用函数实现业务规则:
python复制def is_eligible_for_discount(order):
rules = [
lambda o: o.total > 100,
lambda o: o.customer.is_vip,
lambda o: o.items > 5
]
return any(rule(order) for rule in rules)
27. 函数与测试驱动开发(TDD)
27.1 先写测试
从测试开始设计函数:
python复制# 测试文件
import unittest
class TestStringUtils(unittest.TestCase):
def test_reverse(self):
self.assertEqual(reverse_string("hello"), "olleh")
self.assertEqual(reverse_string(""), "")
self.assertEqual(reverse_string("a"), "a")
# 实现文件
def reverse_string(s):
return s[::-1]
27.2 测试边界条件
确保覆盖各种情况:
python复制class TestMath(unittest.TestCase):
def test_divide(self):
self.assertEqual(divide(4, 2), 2)
self.assertAlmostEqual(divide(1, 3), 0.333, places=3)
with self.assertRaises(ValueError):
divide(1, 0)
with self.assertRaises(TypeError):
divide("1", 2)
27.3 重构保障
测试确保重构不破坏功能:
python复制# 原始实现
def calculate_area(width, height):
return width * height
# 重构后
def calculate_area(width, height=None):
if height is None: # 现在支持正方形
height = width
return width * height
# 原有测试仍然通过,新测试可以添加
28. 函数与性能分析
28.1 性能剖析
找出函数瓶颈:
python复制import cProfile
def slow_function():
# 模拟耗时操作
total = 0
for i in range(100000):
total += i
return total
cProfile.run('slow_function()')
28.2 内存分析
检查函数内存使用:
python复制import tracemalloc
def process_large_data():
data = [x for x in range(100000)]
return sum(data)
tracemalloc.start()
process_large_data()
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
print(top_stats[:10])
28.3 优化策略
基于分析结果优化:
python复制# 优化前
def sum_of_squares(numbers):
return sum([x*x for x in numbers])
# 优化后 - 使用生成器表达式避免临时列表
def sum_of_squares(numbers):
return sum(x*x for x in numbers)
29. 函数与错误处理
29.1 异常层次
设计合理的异常:
python复制class DataValidationError(Exception):
"""基础验证错误"""
class InvalidEmailError(DataValidationError):
"""邮箱格式无效"""
class InvalidAgeError(DataValidationError):
"""年龄不在有效范围内"""
def validate_user(user):
if not is_valid_email(user.email):
raise InvalidEmailError(f"无效邮箱: {user.email}")
if user.age < 0 or user.age > 120:
raise InvalidAgeError(f"无效年龄: {user.age}")
29.2 上下文管理器
资源自动清理:
python复制class DatabaseConnection:
def __enter__(self):
self.conn = connect_to_db()
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
def process_data():
with DatabaseConnection() as conn:
data = conn.query("SELECT * FROM table")
# 处理数据
# 连接自动关闭
29.3 错误恢复
优雅处理失败:
python复制def retry(max_attempts=3, delay=1):
def decorator(func):
def wrapper(*args, **kwargs):
last_error = None
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
last_error = e
time.sleep(delay)
raise last_error
return wrapper
return decorator
@retry(max_attempts=5)
def unreliable_operation():
# 可能失败的操作
...
30. 函数与代码组织
30.1 模块化设计
按功能拆分函数到模块:
code复制myapp/
__init__.py
utils/
__init__.py
math_utils.py # 包含数学相关函数
string_utils.py # 包含字符串处理函数
services/
__init__.py
user_service.py # 用户相关业务函数
30.2 私有函数
使用下划线表示内部函数:
python复制# 在模块中
def public_api():
"""对外公开的接口"""
return _internal_helper()
def _internal_helper():
"""模块内部使用的辅助函数"""
...
30.3 包结构设计
组织大型函数集合:
python复制# 在 myapp/utils/math_utils.py
def add(a, b):
return a + b
def mean(numbers):
return sum(numbers) / len(numbers)
# 在 myapp/utils/__init__.py
from .math_utils import *
from .string_utils import *
# 现在可以这样使用
from myapp.utils import add, mean
