《详解Python的装饰器、迭代器&生成器、re正则表达式、字符串格式化》
Python作为一门简洁而强大的编程语言,其丰富的语法特性为开发者提供了高效的编程工具。本文将深入解析Python中四个核心特性:装饰器(Decorator)、迭代器与生成器(Iterator & Generator)、正则表达式(re模块)以及字符串格式化方法。这些特性不仅体现了Python的优雅设计,也是开发者提升代码质量的关键。
一、装饰器:不修改原函数代码的扩展魔法
装饰器是Python中用于动态修改函数或类行为的语法糖,其核心原理是通过闭包实现高阶函数。装饰器的典型应用场景包括日志记录、权限校验、性能测试等。
1.1 基础装饰器实现
最简单的装饰器接受一个函数作为参数,并返回一个新函数:
def simple_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@simple_decorator
def say_hello():
print("Hello!")
say_hello()
# 输出:
# Before function call
# Hello!
# After function call
1.2 带参数的装饰器
当需要处理被装饰函数的参数时,装饰器需要三层嵌套:
def param_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
return func(*args, **kwargs)
return wrapper
@param_decorator
def greet(name, age):
print(f"Hello {name}, you are {age} years old")
greet("Alice", 25)
1.3 类装饰器与装饰器类
类装饰器通过实现__call__
方法实现:
class ClassDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Class decorator before")
result = self.func(*args, **kwargs)
print("Class decorator after")
return result
@ClassDecorator
def multiply(x, y):
return x * y
1.4 装饰器应用案例
实际开发中,装饰器常用于实现缓存、重试机制等:
import time
from functools import wraps
def cache(func):
cache_dict = {}
@wraps(func)
def wrapper(n):
if n not in cache_dict:
cache_dict[n] = func(n)
return cache_dict[n]
return wrapper
@cache
def fibonacci(n):
if n
二、迭代器与生成器:内存高效的序列处理
迭代器协议要求对象实现__iter__
和__next__
方法,生成器则是通过yield关键字简化的迭代器实现。
2.1 迭代器协议实现
class CountUpTo:
def __init__(self, max):
self.max = max
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.max:
raise StopIteration
self.current += 1
return self.current
for num in CountUpTo(5):
print(num)
2.2 生成器函数
生成器通过yield关键字暂停执行,每次迭代恢复时从yield处继续:
def infinite_sequence():
num = 0
while True:
yield num
num += 1
gen = infinite_sequence()
print(next(gen)) # 0
print(next(gen)) # 1
2.3 生成器表达式
类似列表推导式,但返回生成器对象:
squares = (x**2 for x in range(5))
print(list(squares)) # [0, 1, 4, 9, 16]
2.4 协程与生成器
生成器可通过send()方法接收数据,实现协程功能:
def coroutine_example():
while True:
x = yield
print(f"Received: {x}")
c = coroutine_example()
next(c) # 启动生成器
c.send(10) # 输出: Received: 10
三、re正则表达式:强大的文本处理工具
re模块提供了Perl风格的正则表达式支持,是文本解析的核心工具。
3.1 基本匹配方法
import re
text = "Python 3.10 is awesome"
# 查找所有匹配
matches = re.findall(r"\d+\.\d+", text) # ['3.10']
# 搜索第一个匹配
match = re.search(r"\d+\.\d+", text)
# 完全匹配
is_match = re.fullmatch(r"[A-Za-z ]+", text)
3.2 分组与捕获
date_str = "2023-05-15"
match = re.match(r"(\d{4})-(\d{2})-(\d{2})", date_str)
if match:
year, month, day = match.groups()
print(f"Year: {year}, Month: {month}")
3.3 编译正则对象
对于重复使用的正则表达式,应预先编译:
pattern = re.compile(r"\b\w{4}\b") # 匹配4字母单词
words = pattern.findall("This is a test string") # ['This', 'test']
3.4 替换与分割
# 替换
text = "12 plus 21 equals 33"
new_text = re.sub(r"\d+", "NUM", text) # "NUM plus NUM equals NUM"
# 分割
parts = re.split(r"[,;]", "apple,banana;orange") # ['apple', 'banana', 'orange']
3.5 高级特性
# 非贪婪匹配
text = "content
more"
divs = re.findall(r"(.*?)", text) # ['content', 'more']
# 命名分组
match = re.search(r"(?P\d{4})-(?P\d{2})", "2023-05")
print(match.groupdict()) # {'year': '2023', 'month': '05'}
四、字符串格式化:从%到f-string的演进
Python提供了多种字符串格式化方法,各有适用场景。
4.1 %格式化(传统方法)
name = "Alice"
age = 25
print("Hello %s, you are %d years old" % (name, age))
4.2 str.format()方法
# 位置参数
print("Hello {}, you are {} years old".format(name, age))
# 命名参数
print("Hello {name}, you are {age} years old".format(name=name, age=age))
# 数字格式化
pi = 3.1415926
print("Pi is approximately {:.2f}".format(pi)) # 3.14
4.3 f-string(Python 3.6+推荐)
# 表达式求值
print(f"{name} will be {age + 5} in five years")
# 格式说明
price = 99.99
print(f"Price: ${price:.2f}") # Price: $99.99
# 调试支持
x = 42
print(f"{x=}") # x=42
4.4 模板字符串(安全场景)
from string import Template
t = Template("Hello $name, welcome to $place")
print(t.substitute(name="Bob", place="Python World"))
4.5 国际化支持
# 使用gettext模块实现多语言
import gettext
en = gettext.translation('messages', localedir='locales', languages=['en'])
en.install()
print(_("Hello World"))
关键词:Python装饰器、迭代器与生成器、re正则表达式、字符串格式化、闭包、yield关键字、f-string、正则分组、生成器表达式
简介:本文全面解析Python四大核心特性:装饰器通过闭包实现函数扩展,迭代器与生成器提供内存高效的序列处理,re模块支持强大的正则表达式操作,字符串格式化方法从%到f-string的演进体现了语言设计的进步。每个特性均包含原理说明、代码示例和实际应用场景分析。