- Python 设计模式教程
 - Python 设计模式 - 主页
 - 介绍
 - Python 设计模式 - 要点
 - 模型视图控制器模式
 - Python 设计模式 - 单例
 - Python 设计模式 - 工厂
 - Python 设计模式 - 构建器
 - Python 设计模式 - 原型
 - Python 设计模式 - 外观
 - Python 设计模式 - 命令
 - Python 设计模式 - 适配器
 - Python 设计模式 - 装饰器
 - Python 设计模式 - 代理
 - 责任链模式
 - Python 设计模式 - 观察者
 - Python 设计模式 - 状态
 - Python 设计模式 - 策略
 - Python 设计模式 - 模板
 - Python 设计模式 - 享元
 - 抽象工厂
 - 面向对象
 - 面向对象的概念实现
 - Python 设计模式 - 迭代器
 - 词典
 - 列表数据结构
 - Python 设计模式 - 集
 - Python 设计模式 - 队列
 - 字符串和序列化
 - Python 中的并发
 - Python 设计模式 - 反
 - 异常处理
 
- Python 设计模式资源
 - 快速指南
 - Python 设计模式 - 资源
 - 讨论
 
Python 设计模式 - 反
反模式遵循与预定义设计模式相反的策略。该策略包括解决常见问题的通用方法,可以将其形式化并通常被视为良好的开发实践。通常,反模式是相反的并且是不可取的。反模式是软件开发中使用的某些模式,它们被认为是不好的编程实践。
反模式的重要特征
现在让我们看看反模式的一些重要特征。
正确性
这些模式实际上会破坏你的代码并让你做错误的事情。以下是对此的简单说明 -
class Rectangle(object):
def __init__(self, width, height):
self._width = width
self._height = height
r = Rectangle(5, 6)
# direct access of protected member
print("Width: {:d}".format(r._width))
可维护性
如果一个程序易于理解并根据要求进行修改,则该程序被认为是可维护的。导入模块可以被视为可维护性的一个例子。
import math x = math.ceil(y) # or import multiprocessing as mp pool = mp.pool(8)
反模式示例
以下示例有助于演示反模式 -
#Bad
def filter_for_foo(l):
   r = [e for e in l if e.find("foo") != -1]
   if not check_some_critical_condition(r):
      return None
   return r
res = filter_for_foo(["bar","foo","faz"])
if res is not None:
   #continue processing
   pass
#Good
def filter_for_foo(l):
   r = [e for e in l if e.find("foo") != -1]
   if not check_some_critical_condition(r):
      raise SomeException("critical condition unmet!")
   return r
try:
   res = filter_for_foo(["bar","foo","faz"])
   #continue processing
except SomeException:
   i = 0
while i < 10:
   do_something()
   #we forget to increment i
解释
该示例演示了在 Python 中创建函数的好标准和坏标准。