Advanced Python Features and Their Use Cases
This article introduces twenty advanced Python concepts—including decorators, context managers, generators, metaclasses, multiple inheritance, coroutines, closures, magic methods, dynamic attributes, GIL, async IO, regular expressions, garbage collection, modules, virtual environments, SOLID principles, type annotations, IPC, memory management, and reflection—explaining their typical use cases and providing clear code examples for each.
1. Decorators – Use when you need to add functionality to a function without modifying its source, such as logging or performance measurement.
def my_decorator(func):
def wrapper(*args, **kwargs):
print("在函数调用之前执行")
result = func(*args, **kwargs)
print("在函数调用之后执行")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"你好 {name}!")
say_hello("Alice") # 输出:
# 在函数调用之前执行
# 你好 Alice!
# 在函数调用之后执行2. Context Managers – Use to ensure resources like files or network connections are properly opened and closed.
with open('example.txt', 'w') as 文件:
文件.write('这是一个测试。')
print("文件已关闭。") # 文件会在 with 语句结束后自动关闭3. Generators – Use for handling large or streaming data by yielding items one at a time instead of loading everything into memory.
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num) # 输出斐波那契数列的前10个数字4. Metaclasses – Use when you need to control class creation, such as registering classes or validating attributes.
class Meta(type):
def __new__(cls, name, bases, dct):
print(f"正在创建类 {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
# 输出: 正在创建类 MyClass5. Multiple Inheritance – Use when a class should inherit features from several parent classes; be aware of the method resolution order (MRO).
class A:
def method(self):
print("A 的方法")
class B:
def method(self):
print("B 的方法")
class C(A, B):
pass
c = C()
c.method() # 输出: A 的方法 (根据MRO规则)6. Coroutines – Use for asynchronous programming to handle concurrent tasks without blocking the main thread.
import asyncio
async def greet():
print("你好")
await asyncio.sleep(1) # 模拟异步操作
print("世界")
asyncio.run(greet()) # 异步运行greet函数7. Closures – Use to create function factories or maintain state across calls.
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
times3 = make_multiplier_of(3)
print(times3(9)) # 输出: 278. Magic Methods – Use to customize class behavior such as printing or comparison.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"点({self.x}, {self.y})"
p = Point(1, 2)
print(p) # 输出: 点(1, 2)9. Dynamic Attributes – Use setattr and getattr to add or modify attributes at runtime.
class DynamicClass:
pass
obj = DynamicClass()
setattr(obj, '动态属性', '值')
print(obj.动态属性) # 输出: 值10. Global Interpreter Lock (GIL) – Understand why multithreaded Python programs may not speed up as expected.
import threading
def worker():
print("线程开始工作")
for i in range(10**7):
pass
print("线程结束工作")
thread = threading.Thread(target=worker)
thread.start()
thread.join()
print("主线程继续执行")11. Async IO – Use for efficient handling of I/O‑bound tasks such as network requests or file operations.
import asyncio
async def fetch_data():
print("开始获取数据...")
await asyncio.sleep(1) # 模拟异步操作
print("数据获取完成")
return "数据"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())12. Regular Expressions – Use for complex text pattern matching and string manipulation.
import re
text = "我的邮箱是 [email protected]"
pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
matches = re.findall(pattern, text)
print("找到的电子邮件地址:", matches) # 输出: ['[email protected]']13. Garbage Collection – Use to understand and manually trigger Python's memory cleanup.
import gc
gc.collect() # 强制执行垃圾回收
print(gc.get_count()) # 输出当前垃圾回收计数14. Modules and Packages – Use to organize and import code in a structured way.
# 假设有一个名为 math_operations.py 的模块
from math_operations import add, subtract
print(add(1, 2)) # 输出: 3
print(subtract(5, 3)) # 输出: 215. Virtual Environments – Use to isolate dependencies for different projects.
# 创建并激活虚拟环境
python -m venv myenv
source myenv/bin/activate # Linux/MacOS
# Windows: myenv\Scripts\activate.bat
pip install requests # 安装依赖16. SOLID Principles – Use to write maintainable and extensible object‑oriented code.
# 单一职责原则(Single Responsibility Principle)
class User:
def __init__(self, name):
self.name = name
class UserRepository:
def save(self, user):
print(f"保存用户 {user.name}")
user = User("张三")
repo = UserRepository()
repo.save(user) # 输出: 保存用户 张三17. Type Annotations – Use to improve code readability and enable static analysis.
from typing import List
def greet_all(names: List[str]) -> None:
for name in names:
print(f"你好, {name}!")
greet_all(["张三", "李四"]) # 输出:
# 你好, 张三!
# 你好, 李四!18. Inter‑process Communication (IPC) – Use to exchange data between separate processes via queues, pipes, sockets, etc.
from multiprocessing import Process, Queue
def worker(queue):
queue.put("来自子进程的消息")
if __name__ == '__main__':
q = Queue()
p = Process(target=worker, args=(q,))
p.start()
print(q.get()) # 输出: 来自子进程的消息
p.join()19. Memory Management – Use to understand how Python allocates and releases memory for performance tuning.
import sys
data = [1] * (10**6)
print(f"列表占用内存大小: {sys.getsizeof(data)} 字节")
del data # 删除变量以释放内存20. Reflection and Introspection – Use to dynamically inspect objects' attributes and methods.
class MyClass:
attribute = "这是一个属性"
obj = MyClass()
print(hasattr(obj, 'attribute')) # 输出: True
print(getattr(obj, 'attribute')) # 输出: 这是一个属性
print(dir(obj)) # 输出对象的所有属性和方法Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.