Python 中 10 个关键知识点的深度解析
以下是 Python 中 10 个关键知识点的深度解析,涵盖从基础到进阶的核心概念,每个知识点均附代码示例和实用场景:
1. 上下文管理器(with语句)
作用:自动管理资源(如文件、锁)的生命周期
示例:
with open('data.txt', 'r') as f: # 自动关闭文件
content = f.read()
原理:实现 __enter__() 和 __exit__() 方法的对象即可作为上下文管理器
2. 装饰器(Decorator)
作用:在不修改原函数代码的情况下扩展功能
示例(计时装饰器):
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"耗时: {time.time() - start:.2f}s")
return result
return wrapper
@timer
def heavy_calculation():
time.sleep(1)
3. 生成器(Generator)
作用:惰性计算节省内存
示例:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
print(next(fib)) # 0
print(next(fib)) # 1
4. 类型提示(Type Hints)
作用:提高代码可读性和IDE支持
示例:
def greet(name: str, age: int = 18) -> str:
return f"{name} is {age} years old"
工具链:mypy 静态类型检查器
5. 数据类(@dataclass)
作用:自动生成样板代码(Python 3.7+)
示例:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0 # 默认值
p = Point(1.5, 2.5) # 自动生成__init__和__repr__
6. 海象运算符(:=)
作用:在表达式中赋值(Python 3.8+)
示例:
if (n := len("hello")) > 3:
print(f"长度是{n}") # 长度是5
7. 结构模式匹配(match-case)
作用:类似switch-case的强大模式匹配(Python 3.10+)
示例:
def handle_command(cmd):
match cmd.split():
case ["quit"]:
print("退出程序")
case ["save", filename]:
print(f"保存到{filename}")
case _:
print("未知命令")
8. 并发编程(asyncio)
作用:高性能异步IO
示例(HTTP请求):
import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
html = await fetch("http://example.com")
print(html[:100])
asyncio.run(main())
9. 元类(Metaclass)
作用:控制类的创建行为
示例(自动注册子类):
class PluginMeta(type):
def __init__(cls, name, bases, dct):
super().__init__(name, bases, dct)
if not hasattr(cls, 'plugins'):
cls.plugins = []
else:
cls.plugins.append(cls)
class Plugin(metaclass=PluginMeta):
pass
class MyPlugin(Plugin):
pass
print(Plugin.plugins) # [<class '__main__.MyPlugin'>]
10. 描述符(Descriptor)
作用:精细化控制属性访问
示例(类型验证属性):
class TypedProperty:
def __init__(self, type_):
self.type_ = type_
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, self.type_):
raise TypeError(f"需{self.type_}类型")
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
return instance.__dict__.get(self.name)
class Person:
name = TypedProperty(str)
age = TypedProperty(int)
p = Person()
p.name = "Alice" # 合法
p.age = "25" # 抛出TypeError