在 Python 中,關鍵字(Keywords)是具有特殊含義的保留字,它們用于定義語法和結構。async
是 Python 3.5 引入的關鍵字,用于支持異步編程(Asynchronous Programming)。下面我將詳細講解 async
及其他一些常見關鍵字的用法,并通過代碼示例幫助你理解。
1. async
和 await
(異步編程)
用于編寫異步代碼(基于 asyncio
庫),提高 I/O 密集型任務的效率。
async
:
- 用于聲明一個函數為異步函數(協程函數)。
- 異步函數調用時不會立即執行,而是返回一個協程對象。
await
:
- 用于掛起當前協程,等待另一個協程完成。
示例:
import asyncioasync def fetch_data():print("開始獲取數據...")await asyncio.sleep(2) # 模擬I/O操作(如網絡請求)print("數據獲取完成")return {"data": 123}async def main():task = asyncio.create_task(fetch_data()) # 創建任務print("其他操作...")result = await task # 等待任務完成print("結果:", result)asyncio.run(main()) # 運行入口
輸出:
其他操作...
開始獲取數據...
數據獲取完成
結果: {'data': 123}
2. def
(定義函數)
用于定義普通函數或方法。
def greet(name):return f"Hello, {name}!"
3. class
(定義類)
用于創建類(面向對象編程)。
class Dog:def __init__(self, name):self.name = namedef bark(self):print("Woof!")
4. if/elif/else
(條件判斷)
age = 18
if age < 13:print("兒童")
elif age < 20:print("青少年")
else:print("成人")
5. for
和 while
(循環)
for
用于迭代序列:for i in range(3):print(i) # 輸出 0, 1, 2
while
用于條件循環:count = 0 while count < 3:print(count)count += 1
6. break
和 continue
(循環控制)
break
:退出當前循環。continue
:跳過當前迭代。
for i in range(5):if i == 2:continue # 跳過2if i == 4:break # 終止循環print(i) # 輸出 0, 1, 3
7. try/except/finally
(異常處理)
try:1 / 0
except ZeroDivisionError:print("不能除以零!")
finally:print("無論是否出錯都會執行")
8. with
(上下文管理器)
用于資源管理(如文件操作)。
with open("file.txt", "r") as f:content = f.read() # 文件會自動關閉
9. lambda
(匿名函數)
定義簡單的單行函數。
square = lambda x: x ** 2
print(square(3)) # 輸出 9
10. yield
(生成器函數)
用于生成迭代器,逐步返回值。
def count_up_to(n):for i in range(n):yield i # 每次迭代返回一個值for num in count_up_to(3):print(num) # 輸出 0, 1, 2
11. global
和 nonlocal
(變量作用域)
global
:聲明全局變量。x = 10 def change_x():global xx = 20 change_x() print(x) # 輸出 20
nonlocal
:修改嵌套函數中的變量(Python 3+)。def outer():y = 1def inner():nonlocal yy = 2inner()print(y) # 輸出 2
12. import
和 from
(模塊導入)
import math
from datetime import datetime
總結
async/await
:異步編程的核心,適合網絡請求、文件讀寫等高延遲任務。- 其他關鍵字(如
def
,class
,if
)是 Python 基礎語法的基石。 - 理解關鍵字的作用能幫助你寫出更高效、更清晰的代碼。
如果有其他關鍵字需要詳細解釋,可以告訴我!