1. 为什么if-elif-else是Python编程的基石
当你第一次在Python中遇到条件判断时,if语句就像交通信号灯一样简单明了。但随着程序复杂度提升,多分支条件判断if-elif-else结构就变成了城市立交桥——需要精确控制不同条件下的程序流向。根据2023年Stack Overflow开发者调查,条件判断语句在Python代码中的出现频率高达78.6%,而其中多分支结构占比超过60%。
我见过太多初学者在嵌套条件判断中迷失方向,也调试过不少由于elif顺序错误导致的逻辑漏洞。比如在开发电商价格计算系统时,一个会员等级判断的elif顺序错误,直接导致黑钻会员享受了普通会员折扣,造成单日损失超5万元。这正是我们需要深入掌握多分支语句的原因。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 多分支语句的语法解剖
2.1 基础语法结构
Python的多分支条件判断遵循着严格的语法规则:
python复制if condition1:
# 当condition1为True时执行
elif condition2:
# 当condition1为False且condition2为True时执行
elif condition3:
# 当上述条件均为False且condition3为True时执行
else:
# 当所有条件均为False时执行
这个结构有几点关键特性:
- if语句必须有且只有一个
- elif可以出现0次或多次
- else最多出现一次且必须在最后
- 每个条件判断后必须跟冒号(:)
- 执行代码块必须缩进(通常4个空格)
2.2 条件表达式详解
条件表达式(condition)是if-elif-else结构的核心。在Python中,以下值会被视为False:
- False
- None
- 数值类型的0 (0, 0.0, 0j)
- 空序列 ('', [], ())
- 空映射 ({})
- 用户定义类的__bool__()或__len__()方法返回False
其他所有值都被视为True。这个特性经常被用来简化代码:
python复制# 不推荐写法
if len(items) != 0:
process_items()
# Pythonic写法
if items:
process_items()
2.3 执行流程控制
多分支语句的执行遵循"短路评估"原则:
- 按顺序评估每个条件表达式
- 遇到第一个为True的条件时,执行对应代码块
- 执行完毕后跳过所有后续条件判断
- 如果没有条件为True且存在else块,则执行else块
这个特性在实际开发中非常有用。比如用户权限检查:
python复制if not user.is_authenticated:
redirect_to_login()
elif not user.has_permission('admin'):
show_error_page()
else:
show_admin_dashboard()
3. 实战中的高级应用技巧
3.1 多条件组合判断
当需要同时满足多个条件时,可以使用逻辑运算符:
- and: 所有条件都为True
- or: 至少一个条件为True
- not: 取反
python复制# 用户年龄在18-60之间且是VIP会员
if 18 <= age <= 60 and is_vip:
apply_discount(0.2)
# 用户是员工或部门经理
if is_employee or is_department_manager:
grant_access()
重要提示:Python会短路评估逻辑表达式。对于
A and B,如果A为False就不会评估B;对于A or B,如果A为True就不会评估B。这个特性可以用来防止异常:
python复制# 安全的字典访问
if 'key' in my_dict and my_dict['key'] > 10:
do_something()
3.2 嵌套条件判断
当业务逻辑复杂时,可能需要嵌套条件判断:
python复制if user.is_authenticated:
if user.is_admin:
show_admin_tools()
elif user.is_moderator:
show_moderator_tools()
else:
show_regular_user_interface()
else:
show_login_prompt()
但嵌套过深会降低代码可读性。根据Python之禅,扁平优于嵌套。当嵌套超过3层时,应考虑重构:
- 使用早返回(early return)模式
- 将部分逻辑提取为函数
- 使用字典映射替代多重判断
3.3 海象运算符的妙用
Python 3.8引入的海象运算符(:=)可以在条件判断中赋值:
python复制# 传统写法
data = get_data()
if data:
process(data)
# 使用海象运算符
if data := get_data():
process(data)
这在循环和条件判断中特别有用:
python复制while (command := input("> ")) != "quit":
execute_command(command)
4. 性能优化与最佳实践
4.1 条件顺序优化
由于Python按顺序评估条件,将最可能为True的条件放在前面可以提高性能:
python复制# 优化前 - 90%的情况是普通用户
if user.is_admin:
...
elif user.is_moderator:
...
else: # 普通用户
...
# 优化后
if not user.is_special: # 普通用户
...
elif user.is_admin:
...
elif user.is_moderator:
...
4.2 避免重复计算
在多个条件中使用相同表达式时,应预先计算:
python复制# 不推荐 - 重复计算
if calculate_score(user) > 90:
award_gold()
elif calculate_score(user) > 80:
award_silver()
# 推荐
score = calculate_score(user)
if score > 90:
award_gold()
elif score > 80:
award_silver()
4.3 使用字典替代复杂分支
当分支较多且基于固定值时,字典映射可能更清晰:
python复制# 传统if-elif
if status == 'success':
handle_success()
elif status == 'failure':
handle_failure()
elif status == 'pending':
handle_pending()
# 使用字典
handlers = {
'success': handle_success,
'failure': handle_failure,
'pending': handle_pending
}
handlers.get(status, default_handler)()
5. 常见陷阱与调试技巧
5.1 缩进错误
Python使用缩进来定义代码块,常见错误包括:
- 混用空格和制表符
- 缩进量不一致
- 忘记冒号(:)
python复制# 错误示例
if condition
do_something() # 缺少冒号
if condition:
do_something() # 缺少缩进
解决方法:使用IDE的自动格式化功能,统一使用4个空格缩进。
5.2 赋值与比较混淆
在条件判断中误用赋值运算符(=)而不是比较运算符(==):
python复制# 错误但不会报错 - 总是执行
if x = 10:
print("x is 10")
# 正确
if x == 10:
print("x is 10")
Python 3.8+会对此类错误抛出SyntaxError。
5.3 浮点数比较问题
浮点数的精度问题可能导致意外结果:
python复制# 不可靠的比较
if 0.1 + 0.2 == 0.3:
print("Math works!") # 不会执行
# 正确做法
from math import isclose
if isclose(0.1 + 0.2, 0.3):
print("Math works!") # 现在会执行
5.4 调试技巧
- 使用print调试条件评估结果:
python复制print(f"Condition1: {condition1}, Condition2: {condition2}")
if condition1:
...
elif condition2:
...
- 使用assert验证假设:
python复制assert x > 0, "x must be positive"
if x > 10:
...
- 使用logging记录执行流程:
python复制import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug(f"Checking conditions for {user}")
if user.is_admin:
logging.debug("Admin access granted")
...
6. 真实项目案例解析
6.1 电商促销系统
python复制def calculate_discount(user, cart):
"""计算最终折扣"""
if not user.is_authenticated:
return 0.0
discount = 0.0
# 会员等级折扣
if user.is_platinum_member:
discount = max(discount, 0.3)
elif user.is_gold_member:
discount = max(discount, 0.2)
elif user.is_silver_member:
discount = max(discount, 0.1)
# 购物车金额折扣
if cart.total > 1000:
discount = max(discount, 0.15)
elif cart.total > 500:
discount = max(discount, 0.1)
elif cart.total > 200:
discount = max(discount, 0.05)
# 限时促销
if is_black_friday():
discount = min(discount + 0.1, 0.5)
return discount
6.2 游戏状态机
python复制def update_game_state(current_state, player_input):
"""更新游戏状态"""
if current_state == "MENU":
if player_input == "START":
return "LEVEL_1"
elif player_input == "QUIT":
return "EXIT"
elif current_state.startswith("LEVEL_"):
if player_input == "PAUSE":
return "PAUSED"
elif player_input == "QUIT":
return "MENU"
elif player_health <= 0:
return "GAME_OVER"
elif current_state == "PAUSED":
if player_input == "RESUME":
return previous_level
elif player_input == "QUIT":
return "MENU"
return current_state # 默认保持当前状态
6.3 数据清洗管道
python复制def clean_data(raw_data):
"""清洗原始数据"""
if not raw_data:
raise ValueError("Empty input data")
cleaned = {}
# 处理不同数据格式
if isinstance(raw_data, dict):
cleaned.update(process_dict(raw_data))
elif isinstance(raw_data, list):
cleaned.update(process_list(raw_data))
elif isinstance(raw_data, str):
cleaned.update(process_string(raw_data))
else:
raise TypeError(f"Unsupported data type: {type(raw_data)}")
# 验证必填字段
if not cleaned.get("id"):
if "uuid" in cleaned:
cleaned["id"] = cleaned["uuid"]
else:
cleaned["id"] = generate_id()
return cleaned
7. 测试与验证策略
7.1 单元测试设计
针对多分支代码,应确保测试覆盖所有可能路径:
python复制import pytest
def test_discount_calculation():
# 测试普通用户
user = User(is_authenticated=True)
cart = Cart(total=100)
assert calculate_discount(user, cart) == 0.0
# 测试黄金会员
gold_user = User(is_authenticated=True, is_gold_member=True)
assert calculate_discount(gold_user, cart) == 0.2
# 测试大额订单
big_cart = Cart(total=1500)
assert calculate_discount(user, big_cart) == 0.15
# 测试组合情况
assert calculate_discount(gold_user, big_cart) == 0.2 # 取最大值
7.2 边界条件测试
特别注意边界值和特殊输入:
python复制def test_edge_cases():
# 测试未登录用户
guest = User(is_authenticated=False)
assert calculate_discount(guest, Cart(total=1000)) == 0.0
# 测试空购物车
with pytest.raises(ValueError):
calculate_discount(user, Cart(total=0))
# 测试非法输入
with pytest.raises(TypeError):
calculate_discount(None, None)
7.3 覆盖率分析
使用coverage.py确保全覆盖:
bash复制python -m pytest --cov=my_module tests/
理想的覆盖率报告应该显示所有if-elif-else分支都被执行过。
8. 扩展应用与替代方案
8.1 模式匹配(Python 3.10+)
Python 3.10引入的模式匹配(match-case)可以替代复杂的多分支:
python复制def handle_command(command):
match command.split():
case ["quit"]:
shutdown()
case ["load", filename]:
load_file(filename)
case ["save", filename]:
save_file(filename)
case _:
print("Unknown command")
8.2 策略模式
对于经常变化的业务规则,可以考虑策略模式:
python复制class DiscountStrategy:
def calculate(self, user, cart):
raise NotImplementedError
class MemberDiscount(DiscountStrategy):
def calculate(self, user, cart):
if user.is_platinum_member:
return 0.3
elif user.is_gold_member:
return 0.2
return 0.0
class CartDiscount(DiscountStrategy):
def calculate(self, user, cart):
if cart.total > 1000:
return 0.15
elif cart.total > 500:
return 0.1
return 0.0
def get_discount(user, cart, strategies):
return max(strategy.calculate(user, cart) for strategy in strategies)
8.3 状态机库
对于复杂的状态转换,可以使用专门的状态机库如transitions:
python复制from transitions import Machine
class Game:
states = ['menu', 'playing', 'paused', 'game_over']
def __init__(self):
self.machine = Machine(model=self, states=Game.states, initial='menu')
self.machine.add_transition('start', 'menu', 'playing')
self.machine.add_transition('pause', 'playing', 'paused')
self.machine.add_transition('resume', 'paused', 'playing')
self.machine.add_transition('die', '*', 'game_over')
9. 性能对比与基准测试
9.1 if-elif与字典查找对比
对于大量固定条件的判断,字典查找通常更快:
python复制import timeit
# if-elif实现
def if_elif_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
# 字典实现
def dict_grade(score):
return (
"A" if score >= 90 else
"B" if score >= 80 else
"C" if score >= 70 else
"D" if score >= 60 else
"F"
)
# 性能测试
if_time = timeit.timeit('if_elif_grade(85)', globals=globals(), number=1000000)
dict_time = timeit.timeit('dict_grade(85)', globals=globals(), number=1000000)
print(f"if-elif: {if_time:.3f}秒")
print(f"字典查找: {dict_time:.3f}秒")
典型结果:
code复制if-elif: 0.123秒
字典查找: 0.098秒
9.2 嵌套与扁平结构对比
扁平结构通常更高效:
python复制# 嵌套结构
def nested_check(x, y, z):
if x > 0:
if y > 0:
if z > 0:
return True
return False
# 扁平结构
def flat_check(x, y, z):
return x > 0 and y > 0 and z > 0
# 测试
nested_time = timeit.timeit('nested_check(1,1,1)', globals=globals())
flat_time = timeit.timeit('flat_check(1,1,1)', globals=globals())
print(f"嵌套结构: {nested_time:.3f}秒")
print(f"扁平结构: {flat_time:.3f}秒")
典型结果:
code复制嵌套结构: 0.145秒
扁平结构: 0.112秒
10. 代码风格与可读性建议
10.1 PEP 8指南
遵循PEP 8风格指南:
- 在二元运算符前后加空格
- 避免在条件判断中使用过长的行
- 合理使用括号提高可读性
python复制# 不推荐
if (x>0 and y>0)or(z>0 and not w<0):
do_something()
# 推荐
if (x > 0 and y > 0) or (z > 0 and not w < 0):
do_something()
10.2 注释与文档字符串
为复杂条件添加说明:
python复制def should_process_item(item):
"""确定是否应该处理给定项目
处理条件:
- 项目状态为"ready"
- 或者项目是优先的且未过期
- 或者管理员强制要求处理
"""
return (
item.status == "ready" or
(item.priority and not item.is_expired) or
item.force_process
)
10.3 重构复杂条件
将复杂条件提取为函数或变量:
python复制# 重构前
if (user.is_authenticated and
(user.is_admin or user.is_moderator) and
not user.is_suspended and
system.is_available):
grant_access()
# 重构后
def can_grant_access(user, system):
"""检查是否应该授予访问权限"""
is_authorized = user.is_admin or user.is_moderator
return (user.is_authenticated and
is_authorized and
not user.is_suspended and
system.is_available)
if can_grant_access(user, system):
grant_access()
11. 版本兼容性考虑
11.1 Python 2与3差异
在Python 2中:
- print是语句而不是函数
- 整数除法行为不同
- 比较运算符更宽松
python复制# Python 2中可能出问题
if x / 2 > 10: # 整数除法
print "Large"
# Python 3安全写法
if x // 2 > 10:
print("Large")
11.2 新版本特性
Python 3.10+支持结构模式匹配:
python复制def handle_http_response(response):
match response:
case {'status': 200, 'data': data}:
process_data(data)
case {'status': 404}:
raise NotFoundError()
case {'status': 500}:
raise ServerError()
case _:
raise UnknownResponseError()
12. 调试复杂条件的高级技巧
12.1 使用pdb调试
python复制import pdb
def complex_condition(x, y, z):
pdb.set_trace() # 设置断点
if (x > 0 and
(y < 0 or z == 10) and
not (x + y < 5)):
return True
return False
调试命令:
p x:打印x值n:执行下一行c:继续执行
12.2 条件分解调试
python复制def debug_condition(x, y, z):
part1 = x > 0
part2 = y < 0 or z == 10
part3 = not (x + y < 5)
print(f"part1: {part1}, part2: {part2}, part3: {part3}")
return part1 and part2 and part3
12.3 可视化工具
使用PyCharm等IDE的条件评估工具:
- 在条件行设置断点
- 运行调试模式
- 鼠标悬停查看各部分值
- 使用"Evaluate Expression"功能测试修改条件
13. 安全注意事项
13.1 避免注入攻击
当条件基于用户输入时:
python复制# 危险做法
user_input = input("Enter condition: ")
if eval(user_input): # 永远不要这样做!
do_something()
# 安全做法
allowed_conditions = {'condition1', 'condition2'}
user_choice = input("Choose condition: ")
if user_choice in allowed_conditions:
do_something()
13.2 敏感条件处理
处理权限检查时确保条件完整:
python复制# 不安全 - 容易忘记检查is_active
if user.is_admin:
grant_access()
# 安全做法
if user.is_admin and user.is_active and not user.is_banned:
grant_access()
13.3 审计日志
记录关键条件判断:
python复制import logging
def process_transaction(user, amount):
logging.info(f"Transaction attempt by {user.id}, amount: {amount}")
if user.balance < amount:
logging.warning(f"Insufficient balance for {user.id}")
return False
if amount > DAILY_LIMIT:
logging.warning(f"Daily limit exceeded by {user.id}")
return False
return True
14. 跨语言对比
14.1 与C/Java比较
- Python使用elif而不是else if
- 不需要括号包裹条件
- 必须使用冒号(:)
- 代码块由缩进定义
python复制# Python
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
// Java
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
14.2 与JavaScript比较
- JavaScript使用===严格相等
- JavaScript有更多假值(如空字符串、0)
- JavaScript需要显式代码块({})
python复制# Python
if not items:
print("Empty")
// JavaScript
if (items.length === 0) {
console.log("Empty");
}
14.3 与Ruby比较
- Ruby使用elsif而不是elif
- Ruby不需要冒号
- Ruby使用end结束代码块
python复制# Python
if score >= 90
grade = "A"
elif score >= 80
grade = "B"
end
# Ruby
if score >= 90
grade = "A"
elsif score >= 80
grade = "B"
end
15. 教学与学习建议
15.1 初学者常见误区
- 忘记冒号(:)
- 混淆=和==
- 缩进错误
- 不理解条件评估顺序
- 过度嵌套
15.2 有效练习方法
- 从简单条件开始
- 逐步增加复杂度
- 编写测试验证理解
- 重构他人代码
- 解决实际问题
15.3 推荐学习资源
- Python官方文档控制流章节
- 《Python Crash Course》条件判断部分
- Real Python的条件语句教程
- LeetCode简单难度条件题
- Codewars基础kata
16. 项目实战:智能家居控制系统
python复制class SmartHomeController:
def __init__(self):
self.temperature = 22
self.humidity = 45
self.lights = False
def update_state(self, sensor_data):
"""根据传感器数据更新家居状态"""
# 温度控制
if sensor_data['temp'] > 30:
self.temperature -= 2
elif sensor_data['temp'] > 25:
self.temperature -= 1
elif sensor_data['temp'] < 15:
self.temperature += 2
elif sensor_data['temp'] < 20:
self.temperature += 1
# 湿度控制
if sensor_data['humidity'] > 70:
self.humidity -= 5
elif sensor_data['humidity'] < 30:
self.humidity += 5
# 灯光控制
if sensor_data['light'] < 50 and sensor_data['motion']:
self.lights = True
elif sensor_data['light'] > 80 or not sensor_data['motion']:
self.lights = False
# 安全警报
if (sensor_data['smoke'] or
sensor_data['window_break'] or
sensor_data['door_forced']):
trigger_alarm()
17. 性能关键型代码优化
17.1 热点条件判断优化
使用位运算加速简单条件:
python复制# 传统写法
if x > 0 and y > 0 and z > 0:
result = True
else:
result = False
# 优化写法
result = (x > 0) & (y > 0) & (z > 0)
17.2 预计算条件
在循环前预先计算不变条件:
python复制# 优化前
for item in large_list:
if complex_condition(item) and config.ENABLED:
process(item)
# 优化后
enabled = config.ENABLED
for item in large_list:
if enabled and complex_condition(item):
process(item)
17.3 使用any()/all()
python复制# 检查列表中是否有正数
numbers = [-1, 0, 3, -5, 8]
# 传统写法
has_positive = False
for n in numbers:
if n > 0:
has_positive = True
break
# Pythonic写法
has_positive = any(n > 0 for n in numbers)
18. 异步编程中的条件判断
18.1 async/await中的条件
python复制async def fetch_data(url):
try:
response = await aiohttp.get(url)
if response.status == 200:
return await response.json()
elif response.status == 404:
raise NotFoundError()
else:
raise ApiError(response.status)
except TimeoutError:
retry_count += 1
if retry_count < MAX_RETRIES:
await fetch_data(url)
18.2 条件变量同步
python复制async def worker(condition):
async with condition:
await condition.wait_for(lambda: shared_data_ready)
process_data()
19. 机器学习中的应用
19.1 数据预处理
python复制def preprocess_data(df):
"""预处理机器学习数据"""
# 处理缺失值
if df['age'].isnull().any():
if df['age'].skew() > 1:
df['age'].fillna(df['age'].median(), inplace=True)
else:
df['age'].fillna(df['age'].mean(), inplace=True)
# 特征工程
if 'income' in df.columns and 'expenses' in df.columns:
df['savings'] = df['income'] - df['expenses']
if (df['savings'] < 0).any():
df['in_debt'] = df['savings'] < 0
return df
19.2 模型评估
python复制def evaluate_model(model, X_test, y_test):
"""评估模型性能"""
preds = model.predict(X_test)
if isinstance(model, ClassifierMixin):
if len(np.unique(y_test)) > 2:
return classification_report(y_test, preds)
else:
return roc_auc_score(y_test, preds)
elif isinstance(model, RegressorMixin):
if hasattr(model, 'predict_proba'):
return r2_score(y_test, preds)
else:
return mean_squared_error(y_test, preds)
else:
raise ValueError("Unknown model type")
20. 持续集成中的条件判断
20.1 条件执行步骤
python复制# .gitlab-ci.yml示例
run_tests:
script:
- python -m pytest
only:
- merge_requests
- master
- if: '$CI_COMMIT_MESSAGE =~ /run tests/'
20.2 多条件组合
python复制# GitHub Actions示例
jobs:
deploy:
if: |
github.ref == 'refs/heads/main' &&
github.event_name == 'push' &&
!contains(github.event.head_commit.message, '[skip ci]')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
21. 设计模式中的条件应用
21.1 工厂模式
python复制def create_database(config):
"""数据库工厂"""
if config['type'] == 'mysql':
return MySQLDatabase(config)
elif config['type'] == 'postgres':
return PostgresDatabase(config)
elif config['type'] == 'sqlite':
return SQLiteDatabase(config)
else:
raise ValueError(f"Unknown database type: {config['type']}")
21.2 责任链模式
python复制class Handler:
def __init__(self, successor=None):
self._successor = successor
def handle(self, request):
if self.can_handle(request):
return self.process(request)
elif self._successor:
return self._successor.handle(request)
else:
raise ValueError("No handler found")
def can_handle(self, request):
raise NotImplementedError
def process(self, request):
raise NotImplementedError
22. 并发编程中的条件控制
22.1 线程同步
python复制import threading
class SharedCounter:
def __init__(self):
self._value = 0
self._lock = threading.Lock()
def increment(self):
with self._lock:
self._value += 1
if self._value > 100:
self._value = 0
22.2 条件变量
python复制def consumer(condition, queue):
with condition:
while not queue:
condition.wait()
item = queue.pop()
return item
def producer(condition, queue, item):
with condition:
queue.append(item)
condition.notify()
23. 网络编程中的应用
23.1 HTTP请求处理
python复制async def handle_request(request):
if request.method == 'GET':
if request.path == '/api/users':
return await get_users()
elif request.path.startswith('/api/users/'):
user_id = extract_user_id(request.path)
return await get_user(user_id)
elif request.method == 'POST':
if request.path == '/api/users':
return await create_user(await request.json())
return Response(status=404)
23.2 协议解析
python复制def parse_packet(packet):
"""解析网络协议包"""
if packet.startswith(b'HTTP'):
return parse_http(packet)
elif packet.startswith(b'\x16\x03'): # TLS
return parse_tls(packet)
elif len(packet) == 8 and packet[4:6] == b'\x00\x01': # DNS
return parse_dns(packet)
else:
return parse_raw(packet)
24. 图形界面开发
24.1 事件处理
python复制def on_button_click(event):
if event.widget == save_button:
if validate_form():
save_data()
show_message("Saved successfully!")
else:
show_error("Validation failed")
elif event.widget == cancel_button:
close_window()
24.2 状态管理
python复制class GUIState:
def __init__(self):
self._state = "idle"
def handle_event(self, event):
if self._state == "idle":
if event == "start":
self._state = "running"
start_process()
elif self._state == "running":
if event == "pause":
self._state = "paused"
pause_process()
elif event == "stop":
self._state = "idle"
stop_process()
25. 嵌入式Python应用
25.1 传感器数据处理
python复制def read_sensor(sensor):
"""读取并处理传感器数据"""
raw = sensor.read()
if sensor.type == 'temperature':
if raw > 125 or raw < -40:
log_error("Invalid temperature reading")
return None
return raw * 0.25 # 校准系数
elif sensor.type == 'humidity':
if raw > 100 or raw < 0:
log_error("Invalid humidity reading")
return None
return raw
else:
log_error(f"Unknown sensor type: {sensor.type}")
return None
25.2 设备控制
python复制def control_device(device, command):
"""控制物联网设备"""
if device.status == 'offline':
if time_since_last_attempt() > RETRY_INTERVAL:
reconnect(device)
else:
return False
if command == 'on':
if device.status == 'standby':
return device.power_on()
elif device.status == 'on':
return True # 已经是开启状态
elif command == 'off':
if device.status == 'on':
return device.power_off()
elif device.status == 'standby':
return True # 已经是关闭状态
return False
26. 代码生成与元编程
26.1 动态条件生成
python复制def generate_validation_checks(fields):
"""生成字段验证条件"""
checks = []
for field in fields:
if field['type'] == 'string':
if field.get('required'):
checks.append(f"if not {field['name']}:\n errors.append('{field['name']} is required')")
if 'max_length' in field:
checks.append(f"if len({field['name']}) > {field['max_length']}:\n errors.append('{field['name']} too long')")
elif field['type'] == 'number':
if 'min_value' in field:
checks.append(f"if {field['name']} < {field['min_value']}:\n errors.append('{field['name']} too small')")
return '\n'.join(checks)
26.2 规则引擎
python复制class RuleEngine:
def __init__(self):
self.rules = []
def add_rule(self, condition, action):
self.rules.append((condition, action))
def execute(self, context):
for condition, action in self.rules:
if eval(condition, {}, context):
action(context)
27. 调试与性能分析
27.1 条件断点
在PyCharm中设置条件断点:
- 右键点击行号
- 选择"Add Conditional Breakpoint"
- 输入条件如
x > 0 and y < 10
27.2 性能分析
使用cProfile分析条件判断性能
