模式切换
进阶内容
装饰器
函数装饰器与类装饰器
- 装饰器(Decorator) 是一种修改函数或类行为的语法糖。装饰器可以在不改变原函数或类代码的前提下,扩展或修改其功能。
- 函数装饰器 是通过传递函数对象到装饰器函数中进行的。
python
# 简单的函数装饰器
def my_decorator(func):
def wrapper():
print("Something before the function.")
func()
print("Something after the function.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
输出:
Something before the function.
Hello!
Something after the function.
- 类装饰器 是对类的装饰,类似于函数装饰器,但应用在类上。类装饰器可以在类的行为上添加功能。
python
# 类装饰器
def class_decorator(cls):
cls.decorated = True
return cls
@class_decorator
class MyClass:
pass
print(MyClass.decorated) # True
装饰器的应用场景
装饰器在以下场景中十分常用:
- 日志记录:记录函数的调用和返回值。
- 权限验证:在执行函数前验证用户权限。
- 缓存机制:将函数的返回值缓存,以提高性能。
- 计时功能:记录函数的执行时间。
迭代器与生成器
迭代器
- 迭代器 是实现了
__iter__()
和__next__()
方法的对象。它可以一次返回一个元素,遍历一个序列。
python
class MyIterator:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.limit:
self.current += 1
return self.current
else:
raise StopIteration
my_iter = MyIterator(5)
for number in my_iter:
print(number)
生成器与 yield 关键字
- 生成器 是一种特殊的迭代器,通过使用
yield
关键字来生成值。每次调用yield
会暂停函数的执行,保存状态,并返回一个值;下次使用时会从暂停的地方继续执行。
python
def simple_generator():
yield 1
yield 2
yield 3
gen = simple_generator()
for value in gen:
print(value)
生成器的优点:
- 延迟计算(惰性计算):生成器按需生成值,节省内存。
- 状态保存:每次调用时都保留上次的执行状态。
上下文管理器
自定义上下文管理器
上下文管理器通过 with
语句简化资源管理(如文件操作),其核心是实现 __enter__()
和 __exit__()
方法。
python
class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context")
# 使用自定义上下文管理器
with MyContextManager() as manager:
print("Inside the context")
上下文管理器常用于管理资源的分配与释放,如文件、数据库连接等。
多线程与多进程
threading 和 multiprocessing 模块
threading
模块:用于在单个进程中创建多个线程。线程共享内存空间,开销较小,但受制于 GIL(全局解释器锁)。
python
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
multiprocessing
模块:用于创建多个进程,每个进程有独立的内存空间,不受 GIL 的限制,适用于 CPU 密集型任务。
python
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()
GIL 的概念与作用
- GIL(全局解释器锁) 是 Python 的一个机制,用于确保同一时刻只有一个线程在执行 Python 字节码,从而保证线程安全。它的存在限制了 Python 在多线程中的并发性能,尤其是在 CPU 密集型任务中。
协程与异步编程
asyncio 库
asyncio
是 Python 的异步编程库,用于编写并发的协程程序。与多线程和多进程不同,协程是通过单线程实现并发任务。
python
import asyncio
async def greet():
print("Hello")
await asyncio.sleep(1)
print("World")
# 创建并运行事件循环
asyncio.run(greet())
async 与 await 关键字
async
用于定义异步函数,表示该函数内部可能会包含耗时操作。await
用于暂停异步函数的执行,等待另一个协程完成。
python
async def fetch_data():
print("Fetching data...")
await asyncio.sleep(2) # 模拟耗时操作
print("Data fetched.")
async def main():
await fetch_data()
asyncio.run(main())
协程和异步编程适用于 I/O 密集型任务(如网络请求、文件操作),在提高程序效率方面非常有效。