0
点赞
收藏
分享

微信扫一扫

Python 中关键字的用法与使用技巧

1. Python 关键字概述

1.1 什么是关键字?

关键字是 Python 语言中预定义的保留字,具有特定语法功能,用于构建程序的逻辑结构。它们不能用作变量名、函数名或其他用户定义的标识符。Python 的关键字数量有限,但功能强大,涵盖控制流、数据定义、异常处理等核心领域。

查看关键字列表

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 
 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 
 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 
 'try', 'while', 'with', 'yield']
>>> len(keyword.kwlist)
35

说明

  • Python 3.8+ 有 35 个关键字。
  • 关键字分为逻辑值、控制流、定义/声明、异常处理、模块导入等类别。
  • 使用 keyword.iskeyword("word") 检查是否为关键字:

>>> keyword.iskeyword("if")
True
>>> keyword.iskeyword("hello")
False

1.2 关键字的分类

根据功能,Python 关键字可分为以下几类:

  • 逻辑值TrueFalseNone
  • 控制流ifelifelseforwhilebreakcontinuepass
  • 函数与类定义defclasslambdareturnyield
  • 异常处理tryexceptfinallyraiseassert
  • 作用域与命名空间globalnonlocal
  • 模块与导入importfromas
  • 上下文管理with
  • 异步编程asyncawait
  • 运算符andornotinis.
  • 其他del.

1.3 关键字的重要性

  • 语法核心:关键字定义了 Python 的语法规则,如条件、循环、函数定义。
  • 代码可读性:合理使用关键字使代码逻辑清晰。
  • 效率与简洁性:关键字提供内置优化,简化复杂逻辑。
  • 跨版本兼容:了解关键字演变(如 async/await 3.5+ 引入)确保代码兼容性。

1.4 相关规范

  • PEP 8:代码风格指南,规范关键字使用时的缩进和格式。
  • PEP 3107:函数注解,增强关键字如 def 的表达力。
  • PEP 342/343:定义 with 和 yield 的高级用法。
  • PEP 695(3.12+):类型注解改进,影响 class 等关键字。

2. 逻辑值关键字:True, False, None

2.1 定义与用法

  • True/False:布尔值,表示逻辑真假,是 bool 类型的实例。

is_active = True
is_empty = False

  • None:表示空值或无值,唯一实例为 NoneType

result = None

操作

  • 逻辑运算:andornot

>>> True and False
False
>>> not True
False
>>> True or False
True

  • 比较:返回 True 或 False

>>> 5 > 3
True
>>> x = None
>>> x is None
True

2.2 技巧

  • 短路求值

# 避免不必要的计算
if is_active and expensive_operation():
    pass

  • 默认值:使用 None 作为函数默认参数。

def process(data=None):
    data = [] if data is None else data
    return data

  • 布尔转换:非空/非零值转为 True,空值/零/None 转为 False

>>> bool([])
False
>>> bool("Hello")
True

2.3 应用场景

  • 条件判断

if is_active:
    print("System running")

  • 默认值

def log(message, level=None):
    level = "INFO" if level is None else level
    print(f"[{level}] {message}")

注意事项

  • 避免显式比较布尔值:if is_active: 而非 if is_active == True:
  • 使用 is 检查 Nonex is None 而非 x == None

3. 控制流关键字:if, elif, else, for, while, break, continue, pass

3.1 if, elif, else

定义:用于条件判断。

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
print(grade)  # B

技巧

  • 使用三元表达式简化简单条件:

status = "Pass" if score >= 60 else "Fail"

  • 嵌套条件需注意可读性,尽量展平:

# 差:嵌套过多
if x > 0:
    if y > 0:
        result = x + y
# 好:展平
if x > 0 and y > 0:
    result = x + y

3.2 for, while

定义

  • for:迭代序列。

for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

  • while:条件循环。

count = 0
while count < 5:
    print(count)
    count += 1

技巧

  • 使用 enumerate() 获取索引:

for index, value in enumerate(["a", "b", "c"]):
    print(f"{index}: {value}")

  • zip() 并行迭代:

names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
    print(f"{name}: {age}")

  • 避免无限循环:

while True:
    if condition_met():
        break

3.3 break, continue, pass

  • break:终止循环。

for i in range(10):
    if i == 5:
        break
    print(i)  # 0, 1, 2, 3, 4

  • continue:跳过当前迭代。

for i in range(5):
    if i % 2 == 0:
        continue
    print(i)  # 1, 3

  • pass:占位符,无操作。

def placeholder():
    pass  # 待实现

技巧

  • 使用 break 优化性能:

found = False
for item in large_list:
    if item == target:
        found = True
        break

  • pass 用于调试或占位,避免空代码块错误。

3.4 应用场景

  • 条件处理

if user_role == "admin":
    grant_access()
elif user_role == "user":
    restrict_access()
else:
    deny_access()

  • 数据过滤

evens = [x for x in range(10) if x % 2 == 0]

注意事项

  • 避免过度嵌套,使用逻辑运算符或函数分解。
  • while 循环需确保终止条件。

4. 函数与类定义关键字:def, class, lambda, return, yield

4.1 def

定义:定义函数。

def add(a: int, b: int) -> int:
    return a + b

技巧

  • 使用类型注解:

from typing import List
def sum_list(numbers: List[int]) -> int:
    return sum(numbers)

  • 默认参数:

def greet(name: str = "Guest") -> str:
    return f"Hello, {name}!"

4.2 class

定义:定义类。

class Person:
    def __init__(self, name: str):
        self.name = name

    def greet(self) -> str:
        return f"Hello, {self.name}!"

技巧

  • 使用 @classmethod 和 @staticmethod

class MathUtils:
    @staticmethod
    def square(n: int) -> int:
        return n * n

  • 类型注解(3.12+,PEP 695):

class Stack[T]:
    def push(self, item: T) -> None:
        pass

4.3 lambda

定义:匿名函数。

double = lambda x: x * 2
print(double(5))  # 10

技巧

  • 用于简单逻辑:

numbers = [1, 2, 3]
sorted_numbers = sorted(numbers, key=lambda x: -x)  # 降序

  • 避免复杂逻辑,保持可读性。

4.4 return

定义:返回函数结果。

def divide(a: float, b: float) -> float:
    return a / b if b != 0 else float("inf")

技巧

  • 多值返回:

def get_stats(numbers: List[int]) -> tuple:
    return min(numbers), max(numbers)
min_val, max_val = get_stats([1, 2, 3])

4.5 yield

定义:生成器函数,返回迭代器。

def fib(n: int):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

技巧

  • 节省内存:

# 列表:占用大量内存
lst = [x**2 for x in range(1000000)]
# 生成器:按需生成
gen = (x**2 for x in range(1000000))

  • 使用 yield from 简化嵌套:

def sub_gen():
    yield 1
    yield 2
def main_gen():
    yield from sub_gen()

4.6 应用场景

  • 函数:模块化代码。

def calculate_total(items: List[float]) -> float:
    return sum(items)

  • :面向对象编程。

class TrafficLight:
    def __init__(self, state: str):
        self.state = state

  • 生成器:处理大数据。

def read_large_file(file_path: str):
    with open(file_path) as f:
        for line in f:
            yield line

注意事项

  • 函数名遵循 PEP 8(小写+下划线)。
  • lambda 避免复杂逻辑。
  • yield 适合流式数据处理。

5. 异常处理关键字:try, except, finally, raise, assert

5.1 try, except, finally

定义:处理异常。

try:
    result = 10 / 0
except ZeroDivisionError:
    result = float("inf")
finally:
    print("Cleanup done")

技巧

  • 捕获特定异常:

try:
    value = int("abc")
except ValueError as e:
    print(f"Invalid input: {e}")

  • finally 用于资源清理:

try:
    f = open("data.txt")
finally:
    f.close()

5.2 raise

定义:抛出异常。

def check_age(age: int):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

技巧

  • 自定义异常:

class CustomError(Exception):
    pass
raise CustomError("Something went wrong")

5.3 assert

定义:调试断言,条件为 False 时抛出 AssertionError

def divide(a: float, b: float) -> float:
    assert b != 0, "Divider cannot be zero"
    return a / b

技巧

  • 用于开发测试:

assert len(data) > 0, "Data cannot be empty"

  • 生产环境中可禁用:python -O

5.4 应用场景

  • 文件操作

try:
    with open("data.txt") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found")

  • 输入验证

def process_input(value: str):
    if not value.isdigit():
        raise ValueError("Input must be numeric")
    return int(value)

注意事项

  • 避免捕获所有异常(except:),指定具体类型。
  • assert 仅用于调试,非生产验证。

6. 作用域与命名空间关键字:global, nonlocal

6.1 global

定义:声明全局变量。

count = 0
def increment():
    global count
    count += 1

技巧

  • 谨慎使用,优先通过参数传递:

def increment(count: int) -> int:
    return count + 1

6.2 nonlocal

定义:声明外层函数变量。

def outer():
    x = 0
    def inner():
        nonlocal x
        x += 1
    inner()
    print(x)  # 1

技巧

  • 用于嵌套函数修改外层变量。
  • 避免过多嵌套,考虑类或函数分解。

6.3 应用场景

  • 计数器

def create_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

  • 配置管理

settings = {}
def update_setting(key: str, value):
    global settings
    settings[key] = value

注意事项

  • 避免滥用 global/nonlocal,可能导致代码难以维护。
  • 使用类或闭包替代复杂作用域操作。

7. 模块与导入关键字:import, from, as

7.1 import, from

定义:导入模块或模块中的对象。

import math
from datetime import datetime

技巧

  • 导入特定对象:

from math import sin, cos

  • 避免 from module import *(污染命名空间)。

7.2 as

定义:为导入对象指定别名。

import numpy as np
import pandas as pd

技巧

  • 统一别名(如 nppd)提高代码一致性。
  • 用于避免命名冲突:

from module1 import func as func1
from module2 import func as func2

7.3 应用场景

  • 科学计算

import math as m
print(m.pi)

  • 数据分析

from pandas import DataFrame as DF
df = DF({"col": [1, 2, 3]})

注意事项

  • 按 PEP 8 排序导入:标准库、第三方库、本地模块。
  • 避免循环导入。

8. 上下文管理关键字:with

定义:管理资源(如文件、锁)的上下文。

with open("data.txt", "r") as f:
    data = f.read()

技巧

  • 自定义上下文管理器:

from contextlib import contextmanager
@contextmanager
def timer():
    start = time.time()
    yield
    print(f"Elapsed: {time.time() - start}")
with timer():
    time.sleep(1)

  • 嵌套上下文:

with open("in.txt") as fin, open("out.txt", "w") as fout:
    fout.write(fin.read())

应用场景

  • 文件操作:自动关闭文件。
  • 数据库连接

with sqlite3.connect("db.sqlite3") as conn:
    conn.execute("SELECT * FROM table")

注意事项

  • 确保上下文管理器实现 __enter__ 和 __exit__
  • 避免在 with 块中执行耗时操作。

9. 异步编程关键字:async, await

9.1 async, await

定义:支持异步编程,处理并发任务。

import asyncio
async def say_hello():
    await asyncio.sleep(1)
    return "Hello"
async def main():
    result = await say_hello()
    print(result)
asyncio.run(main())

技巧

  • 使用 asyncio.gather 并发运行:

async def task1():
    await asyncio.sleep(1)
    return "Task 1"
async def task2():
    await asyncio.sleep(1)
    return "Task 2"
async def main():
    results = await asyncio.gather(task1(), task2())
    print(results)

应用场景

  • 网络请求

import aiohttp
async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

注意事项

  • await 只能在 async 函数中使用。
  • 使用 asyncio.run() 运行顶层协程。

10. 运算符关键字:and, or, not, in, is

10.1 and, or, not

定义:逻辑运算。

x = 5
if x > 0 and x < 10:
    print("In range")

技巧

  • 短路求值:

if data and data[0]:
    process(data[0])

10.2 in, is

  • in:检查成员关系。

if "a" in ["a", "b", "c"]:
    print("Found")

  • is:检查对象身份。

x = None
if x is None:
    print("x is None")

技巧

  • in 用于集合查找(set 更快):

s = set([1, 2, 3])
if 2 in s:  # O(1)
    print("Found")

  • is 用于单例检查(如 None)。

应用场景

  • 数据验证

if user_id not in valid_ids:
    raise ValueError("Invalid ID")

注意事项

  • is 比较对象身份,非值:[1, 2] is [1, 2] 为 False
  • in 对大列表慢,优先用集合。

11. 其他关键字:del

定义:删除变量、列表元素或字典键。

x = [1, 2, 3]
del x[1]
print(x)  # [1, 3]

技巧

  • 删除字典键:

d = {"a": 1, "b": 2}
del d["a"]

  • 删除变量:

x = 42
del x

应用场景

  • 清理内存

large_data = [1] * 1000000
del large_data
import gc
gc.collect()

注意事项

  • 确保变量存在,否则抛出 NameError
  • 删除列表切片需小心索引变化。

12. 高级技巧与优化

12.1 关键字与类型注解

结合 PEP 484/695 使用类型注解:

from typing import List
def filter_evens(numbers: List[int]) -> List[int]:
    return [x for x in numbers if x % 2 == 0]

12.2 性能优化

  • for vs whilefor 更适合确定迭代,while 适合动态条件。

# 快:for
for i in range(1000):
    pass
# 慢:while
i = 0
while i < 1000:
    i += 1

  • yield:节省内存处理大数据。

def large_range(n):
    for i in range(n):
        yield i

12.3 调试与断言

  • 使用 assert 调试:

def process(data):
    assert isinstance(data, list), "Input must be a list"
    return data

  • 使用 try/except 捕获运行时错误。

12.4 异步优化

  • 并发任务:

async def process_batch(items):
    tasks = [process_item(item) async for item in items]
    return await asyncio.gather(*tasks)

13. 实际应用场景

13.1 数据分析

场景:处理 CSV 数据。

import pandas as pd
def load_data(file_path: str) -> pd.DataFrame:
    try:
        df = pd.read_csv(file_path)
    except FileNotFoundError:
        raise ValueError("File not found")
    return df

13.2 游戏开发(参考 TrafficFlowGame)

场景:红绿灯逻辑。

class TrafficLight:
    def __init__(self):
        self.state = "red"
    def change(self):
        if self.state == "red":
            self.state = "green"
        elif self.state == "green":
            self.state = "yellow"
        else:
            self.state = "red"

13.3 API 开发

场景:FastAPI 端点。

from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
async def get_items():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.example.com") as resp:
            return await resp.json()

13.4 算法实现

场景:二分查找。

def binary_search(arr: List[int], target: int) -> int:
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

举报

相关推荐

0 条评论