装饰器(Decorators)
装饰器是 Python 的高级特性,用于修改函数行为而无需更改其代码。
def my_decorator(func):
def wrapper():
print("装饰器前置操作")
func()
print("装饰器后置操作")
return wrapper
@my_decorator
def say_hello():
print("Hello")
say_hello()
上下文管理器(Context Managers)
使用 with
语句管理资源,确保正确释放。
with open("file.txt", "r") as f:
content = f.read()
元编程(Metaprogramming)
通过 type
或 metaclass
实现动态类创建。
class Meta(type):
def __new__(cls, name, bases, attrs):
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
并发编程(Concurrent Programming)
使用 async/await
实现异步操作,提升性能。
import asyncio
async def my_async_function():
await asyncio.sleep(1)
print("异步完成")
asyncio.run(my_async_function())