资料内容:
一、Python高级特性
1.1 上下文管理器与with语句
# 自定义上下文管理器
class DatabaseConnection:
def __enter__(self):
self.conn = create_connection()
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
# 使用上下文管理器
with DatabaseConnection() as conn:
conn.execute_query("SELECT * FROM users")
1.2 生成器与协程
# 生成器表达式
squares = (x*x for x in range(10000))
# 协程
def coroutine():
while True:
received = yield
print(f"Received: {received}")
# 使用协程
c = coroutine()
next(c) # 预激协程
c.send("Hello")