"Python pattern" 主要可能指以下三种情况:

- 设计模式:这是最常见和最核心的含义,指在软件开发中反复出现的问题的通用、可复用的解决方案。
- 正则表达式:在 Python 中,
re模块用于处理正则表达式,这是一种用来匹配字符串模式的强大工具。 - 字符串格式化模式:指在
str.format()或 f-string 中使用的特定格式化语法。
下面我们逐一详细介绍。
设计模式
这是“Python pattern”最普遍的含义,设计模式不是 Python 特有的,它们是软件工程中一套成熟的设计思想,旨在让代码更加灵活、可维护和可扩展,Python 凭借其简洁的语法,可以非常优雅地实现各种设计模式。
常见的设计模式分类:
设计模式通常分为三大类:创建型、结构型和行为型。
a) 创建型模式
关注对象的创建过程。

-
单例模式
-
目的:保证一个类只有一个实例,并提供一个全局访问点。
-
Python 实现:Python 有多种实现方式,最常用的是使用装饰器或元类。
-
示例 (使用装饰器):
(图片来源网络,侵删)def singleton(cls): instances = {} def get_instance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return get_instance @singleton class President: def __init__(self, name): self.name = name president1 = President("Washington") president2 = President("Adams") print(president1 is president2) # 输出: True,它们是同一个实例
-
-
工厂模式
-
目的:定义一个用于创建对象的接口,让子类决定实例化哪一个类,将实例的创建延迟到子类。
-
Python 实现:通过一个工厂类或工厂方法来返回不同的对象。
-
示例:
class Dog: def speak(self): return "Woof!" class Cat: def speak(self): return "Meow!" class AnimalFactory: def get_pet(self, pet_type): pets = { "dog": Dog, "cat": Cat, } return pets[pet_type]() factory = AnimalFactory() my_dog = factory.get_pet("dog") my_cat = factory.get_pet("cat") print(my_dog.speak()) # 输出: Woof! print(my_cat.speak()) # 输出: Meow!
-
b) 结构型模式
关注类和对象的组合。
-
适配器模式
- 目的:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
- Python 实现:非常常见,
tkinter的StringVar就是一个适配器,将 Python 字符串与 GUI 组件的值绑定起来。
-
装饰器模式
-
目的:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式相比生成子类更为灵活。
-
Python 实现:Python 的 语法糖就是装饰器模式的完美体现。
-
示例:
def my_timer(func): import time def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"{func.__name__} executed in {end_time - start_time:.4f} s") return result return wrapper @my_timer def long_running_task(): import time time.sleep(2) long_running_task() # 输出: long_running_task executed in 2.0001 s
-
c) 行为型模式
关注对象之间的通信和职责分配。
-
观察者模式
-
目的:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
-
Python 实现:常用于事件处理系统。
-
示例:
class Subject: def __init__(self): self._observers = [] self._state = None def attach(self, observer): if observer not in self._observers: self._observers.append(observer) def detach(self, observer): try: self._observers.remove(observer) except ValueError: pass def notify(self): for observer in self._observers: observer.update(self) @property def state(self): return self._state @state.setter def state(self, value): self._state = value self.notify() class Observer: def update(self, subject): print(f"Observer: The subject's state has changed to {subject.state}") subject = Subject() observer1 = Observer() observer2 = Observer() subject.attach(observer1) subject.attach(observer2) subject.state = 123 # 通知所有观察者 # 输出: # Observer: The subject's state has changed to 123 # Observer: The subject's state has changed to 123
-
正则表达式
正则表达式是用于处理字符串的强大工具,它可以让你按照特定的“模式”来搜索、匹配、替换和分割字符串,在 Python 中,主要通过 re 模块使用。
re 模块的核心功能:
re.match(): 从字符串的开头进行匹配。re.search(): 扫描整个字符串,返回第一个匹配项。re.findall(): 找到所有匹配项,并以列表形式返回。re.sub(): 替换字符串中匹配到的模式。
常见正则表达式模式:
| 模式 | 描述 | 示例 |
|---|---|---|
| 匹配除换行符外的任意单个字符 | a.c 匹配 "abc", "aac" |
|
| 匹配前面的子表达式零次或多次 | a* 匹配 "", "a", "aa" |
|
| 匹配前面的子表达式一次或多次 | a+ 匹配 "a", "aa" |
|
| 匹配前面的子表达式零次或一次 | a? 匹配 "", "a" |
|
^ |
匹配字符串的开始 | ^hello 匹配 "hello world" |
| 匹配字符串的结束 | world$ 匹配 "hello world" |
|
\d |
匹配一个数字,等同于 [0-9] |
\d{3} 匹配 "123" |
\w |
匹配一个单词字符(字母、数字、下划线) | \w+ 匹配 "Python" |
[] |
字符集,匹配其中的任意一个字符 | [abc] 匹配 "a", "b", 或 "c" |
示例:
import re
text = "My phone number is 123-456-7890, and my friend's is 987-654-3210."
# 查找所有电话号码
pattern = r"\d{3}-\d{3}-\d{4}"
phone_numbers = re.findall(pattern, text)
print(phone_numbers)
# 输出: ['123-456-7890', '987-654-3210']
# 验证邮箱格式
email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
valid_emails = ["test@example.com", "user.name@domain.co.uk"]
invalid_emails = ["test@", "domain.com"]
for email in valid_emails + invalid_emails:
if re.match(email_pattern, email):
print(f"'{email}' 是一个有效的邮箱地址。")
else:
print(f"'{email}' 不是一个有效的邮箱地址。")
字符串格式化模式
这是指在格式化字符串时使用的特定语法,用来定义输出数据的格式。
旧式字符串格式化 ( 操作符)
这是 Python 早期版本遗留下来的方式,类似于 C 语言的 printf。
name = "Alice"
age = 30
print("Hello, %s. You are %d years old." % (name, age))
# 输出: Hello, Alice. You are 30 years old.
str.format() 方法
更现代、更灵活的格式化方式。
name = "Bob"
age = 25
print("Hello, {}. You are {} years old.".format(name, age))
# 输出: Hello, Bob. You are 25 years old.
# 也可以使用位置索引或关键字参数
print("Hello, {0}. You are {1} years old.".format(name, age))
print("Hello, {n}. You are {a} years old.".format(n=name, a=age))
f-strings (格式化字符串字面量)
Python 3.6+ 引入,是目前最推荐、最简洁、性能也最高的方式。
name = "Charlie"
age = 35
print(f"Hello, {name}. You are {age} years old.")
# 输出: Hello, Charlie. You are 35 years old.
# 可以直接在花括号内执行表达式
print(f"Next year, {name} will be {age + 1} years old.")
# 输出: Next year, Charlie will be 36 years old.
格式化规范迷你语言
在 format() 和 f-strings 中,可以使用 后跟一个格式说明符来控制数字的显示格式。
pi = 3.1415926
# 保留两位小数
print(f"Pi is approximately {pi:.2f}")
# 输出: Pi is approximately 3.14
# 科学计数法,保留一位小数
print(f"Pi in scientific notation: {pi:.1e}")
# 输出: Pi in scientific notation: 3.1e+00
# 数字补零,总宽度为5
print(f"Number with padding: {42:05d}")
# 输出: Number with padding: 00042
| 术语 | 核心概念 | 主要用途 | Python 相关模块/语法 |
|---|---|---|---|
| 设计模式 | 可复用的软件设计解决方案 | 提高代码质量、可维护性、扩展性 | 无特定模块,是编程思想(如 装饰器) |
| 正则表达式 | 匹配字符串中特定模式的规则 | 文本搜索、解析、验证、替换 | re 模块 |
| 字符串格式化模式 | 定义输出数据格式的语法 | 生成格式化的字符串 | 操作符, str.format(), f-string (f"...") |
当别人提到 "Python pattern" 时,你需要根据上下文来判断他具体指的是设计模式、正则表达式还是字符串格式化,在大多数情况下,尤其是在软件开发的讨论中,它都指的是设计模式。
