Python高级编程不仅是语法的堆砌,更是对语言本质、性能优化、设计模式和系统级开发的深度理解。本文将结合 语言特性、工具链、实战项目,从 语法细节 到 分布式系统 全面解析,助你成为Python领域专家。
|
和&
字典操作)# 3.13新增功能示例:精确的浮点数运算
from math import isclose
print(0.1 + 0.2 == 0.3) # False(浮点精度问题)
print(isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)) # True
venv
、conda
、poetry
的对比与实践pdb
交互式调试memory_profiler
内存分析cProfile
性能分析flake8
静态检查mypy
类型检查black
代码格式化class NonNegative:
def __set__(self, instance, value):
if value < 0:
raise ValueError("值必须非负")
instance.__dict__[self.name] = value
def __set_name__(self, owner, name):
self.name = name
class Product:
price = NonNegative()
p = Product()
p.price = 100 # 正常
p.price = -50 # 抛出ValueError
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Logger(metaclass=SingletonMeta):
pass
logger1 = Logger()
logger2 = Logger()
print(logger1 is logger2) # True
exec()
与eval()
的高级用法ast
模块解析与修改代码import ast
class AddPrintTransformer(ast.NodeTransformer):
def visit_FunctionDef(self, node):
new_body = [ast.Expr(value=ast.Constant(value="Entering function"))] + node.body
return ast.copy_location(ast.FunctionDef(name=node.name, body=new_body, args=node.args), node)
code = """
def add(a, b):
return a + b
"""
tree = ast.parse(code)
new_tree = AddPrintTransformer().visit(tree)
exec(compile(new_tree, filename="" , mode="exec"))
add(1, 2) # 输出:Entering function
multiprocessing
规避GILfrom multiprocessing import Pool
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
if __name__ == "__main__":
with Pool() as p:
results = p.map(fib, [35]*4)
print(results)
asyncio
事件循环:从await
到async def
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, "https://example.com") for _ in range(10)]
results = await asyncio.gather(*tasks)
print(f"获取{len(results)}个页面")
asyncio.run(main())
# example.pyx
def sum_cython(int n):
cdef int i, s = 0
for i in range(n):
s += i
return s
$ cythonize -i example.pyx
# Python版本:O(n)
# Cython版本:O(1)(编译为C代码)
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class AnimalFactory:
def get_animal(self, animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
else:
raise ValueError("未知类型")
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self):
for observer in self._observers:
observer.update(self)
class Observer:
def update(self, subject):
print("事件已触发!")
FastAPI
构建REST APIfrom fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
# 生产者(RabbitMQ)
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
channel.basic_publish(
exchange='',
routing_key='task_queue',
body='Hello World!',
properties=pika.BasicProperties(delivery_mode=2,)
)
setuptools
与poetry
构建包# .github/workflows/ci.yml
name: Python CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python 3.10
uses: actions/setup-python@v2
with:
python-version: "3.10"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
- name: Test with pytest
run: pytest
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-python-app
spec:
replicas: 3
selector:
matchLabels:
app: my-python-app
template:
metadata:
labels:
app: my-python-app
spec:
containers:
- name: my-python-container
image: my-python-image:latest
ports:
- containerPort: 8080
objgraph
可视化内存引用import objgraph
objgraph.show_most_common_types() # 输出对象类型统计
objgraph.show_refs([obj], filename='refs.png') # 生成内存图
# 低效写法
s = ""
for line in lines:
s += line
# 高效写法
s = "".join(lines)
SQLAlchemy
优化查询from sqlalchemy.orm import Session
from sqlalchemy import select
with Session(engine) as session:
# 预加载关联对象
stmt = select(User).options(selectinload(User.orders))
users = session.scalars(stmt).all()
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'redis'})
@app.route('/cache')
@cache.cached(timeout=50)
def cached_view():
return "缓存内容"
import numpy as np
a = np.random.rand(1000000)
b = np.random.rand(1000000)
# 低效循环
c = [a[i] + b[i] for i in range(len(a))] # 约1秒
# 高效向量化
c = a + b # 几乎瞬间完成
pdb
、ipdb
、PyCharm调试器
cProfile
、Py-Spy
(实时火焰图)flake8
、mypy
、black
通过本教程,你将掌握:
下一步建议:
mypy
为现有代码添加类型注解。Cython
优化CPU密集型函数。