資料內(nèi)容:
一、Python高級(jí)特性
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 生成器與協(xié)程
# 生成器表達(dá)式
squares = (x*x for x in range(10000))
# 協(xié)程
def coroutine():
while True:
received = yield
print(f"Received: {received}")
# 使用協(xié)程
c = coroutine()
next(c) # 預(yù)激協(xié)程
c.send("Hello")