Advanced Python Techniques: 10 In-Depth Code Examples
This article presents ten advanced Python techniques—including list comprehensions, lambda functions, decorators, context managers, generators, metaclasses, asyncio coroutines, enums, slicing, and exception handling—each illustrated with detailed code examples to help readers deepen their mastery of Python programming.
🔥 Introduction: Python’s powerful features and flexibility attract many developers; this guide moves beyond basic syntax to focus on advanced Python applications through at least ten detailed code examples, guiding readers toward Python mastery.
1️⃣ List Comprehensions and Generator Expressions
# 列表推导式:创建平方数列表
squares = [x**2 for x in range(1, 6)]
print(squares) # 输出:[1, 4, 9, 16, 25]
# 生成器表达式:创建平方数生成器
gen_squares = (x**2 for x in range(1, 6))
for square in gen_squares:
print(square) # 分别输出:1, 4, 9, 16, 252️⃣ Lambda Functions and map/reduce/filter
# 匿名函数应用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # 输出:[1, 4, 9, 16, 25]
# reduce函数求和
from functools import reduce
total = reduce(lambda x, y: x+y, numbers)
print(total) # 输出:15
# filter函数筛选偶数
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出:[2, 4]3️⃣ Decorators
# 定义一个计时装饰器
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__}执行耗时:{end_time - start_time}秒")
return result
return wrapper
@timing_decorator
def long_running_task():
time.sleep(2)
long_running_task()4️⃣ Context Managers and with Statement
# 定义一个简单的上下文管理器
class FileOpener:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
# 使用with语句读取文件
with FileOpener('example.txt') as file:
content = file.read()
print(content)5️⃣ Iterators and Generators
# 创建一个无限序列生成器
def infinite_sequence(start=0):
while True:
yield start
start += 1
# 使用生成器
gen = infinite_sequence(1)
print(next(gen) # 输出:1)
print(next(gen) # 输出:2)6️⃣ Metaclasses
# 元类示例:所有通过此元类创建的类都将自动添加一个say_hello方法
class Meta(type):
def __new__(cls, name, bases, attrs):
attrs['say_hello'] = lambda self: print(f'Hello from {name}')
return super().__new__(cls, name, attrs)
class MyClass(metaclass=Meta):
pass
obj = MyClass()
obj.say_hello() # 输出:Hello from MyClass7️⃣ Coroutines and asyncio Library
import asyncio
# 协程示例
async def hello_world():
print('Hello')
await asyncio.sleep(1)
print('World')
# 运行协程
asyncio.run(hello_world()) # 输出顺序:Hello -> (等待1秒) -> World8️⃣ Enum
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# 使用枚举
print(Color.RED.value) # 输出:1
print(Color['RED']) # 输出:9️⃣ Slicing and Chained Indexing
# 切片与链式索引
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 获取矩阵第二列
second_column = [row[1] for row in matrix]
print(second_column) # 输出:[2, 5, 8]
# 链式索引
print(matrix[1][1]) # 输出:510️⃣ Exception Handling and Context Association
try:
raise ValueError('An error occurred!')
except ValueError as ve:
print(f'捕获到异常:{ve}')
# 上下文关联
try:
with open('non_existent_file.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print('文件不存在')🌟 Conclusion: By exploring these ten advanced Python applications, readers can appreciate Python’s depth and breadth, encouraging hands‑on practice to master the underlying principles and apply them flexibly in future coding projects.
Follow our public account for more Python insights and deep dives.
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.