1|# 从Java到Python的思维转变:项目实战 2| 3|## 最后一篇:从思维到实战 4| 5|前面9篇讲了语法、数据结构、函数、OOP、并发、标准库。最后一篇讲思维方式的转变和实战项目。 6| 7|## 一、Pythonic代码:放下Java的仪式感 8| 9|### 反例 vs 正解 10| 11|
12|# 遍历列表
13|# Java风格
14|for i in range(len(items)):
15| print(items[i])
16|# Pythonic
17|for item in items:
18| print(item)
19|
20|# 遍历字典
21|# Java风格
22|for key in d.keys():
23| print(key, d[key])
24|# Pythonic
25|for key, value in d.items():
26| print(key, value)
27|
28|# 交换变量
29|a, b = b, a # Python一行搞定
30|
31|# 判断是否为空
32|if mylist: # Pythonic(不是 if len(mylist) > 0)
33| pass
34|
35|# 字符串拼接
36|result = ",".join(items) # 不要用 + 循环拼接
37|
38|# 三元表达式
39|status = "成年" if age >= 18 else "未成年"
40|
41|# 带索引遍历
42|for i, item in enumerate(items):
43| print(f"{i}: {item}")
44|
45|
46|### 解包赋值
47|
48| 49|# 多变量赋值
50|name, age, city = "张三", 25, "北京"
51|
52|# 星号解包
53|first, *rest = [1, 2, 3, 4, 5]
54|# first=1, rest=[2,3,4,5]
55|
56|first, *middle, last = [1, 2, 3, 4, 5]
57|# first=1, middle=[2,3,4], last=5
58|
59|# 交换多个变量
60|a, b, c = 1, 2, 3
61|a, b, c = c, a, b # 右移一位
62|
63|
64|## 二、设计模式在Python中的简化
65|
66|### 单例模式
67|
68| 69|# Java需要枚举或静态内部类
70|# Python:模块就是单例
71|# config.py
72|DATABASE_URL = "mysql://localhost/db"
73|DEBUG = True
74|# 直接import,Python模块天然是单例
75|
76|# 如果需要类级别的单例
77|class Singleton:
78| _instance = None
79| def new(cls):
80| if cls._instance is None:
81| cls._instance = super().new(cls)
82| return cls._instance
83|
84|
85|### 策略模式
86|
87| 88|# Java需要接口+多个实现类
89|# Python用函数就行
90|
91|def price_normal(price): return price
92|def price_vip(price): return price * 0.8
93|def price_svip(price): return price * 0.6
94|
95|# 直接传函数
96|def checkout(price, strategy):
97| return strategy(price)
98|
99|print(checkout(100, price_vip)) # 80
100|
101|
102|### 观察者模式
103|
104| 105|class EventEmitter:
106| def init(self):
107| self._events = {}
108| def on(self, event, callback):
109| self._events.setdefault(event, []).append(callback)
110| def emit(self, event, args, *kwargs):
111| for cb in self._events.get(event, []):
112| cb(args, *kwargs)
113|
114|emitter = EventEmitter()
115|emitter.on("data", lambda d: print(f"收到: {d}"))
116|emitter.emit("data", "hello")
117|
118|
119|### 装饰器实现AOP
120|
121| 122|import time
123|from functools import wraps
124|
125|def timer(func):
126| @wraps(func) # 保留原函数元信息
127| def wrapper(args, *kwargs):
128| start = time.time()
129| result = func(args, *kwargs)
130| print(f"{func.name} 耗时 {time.time()-start:.2f}s")
131| return result
132| return wrapper
133|
134|@timer
135|def slow_function():
136| time.sleep(1)
137|
138|
139|## 三、FastAPI:Python版Spring Boot
140|
141|### 基础项目
142|
143| 144|from fastapi import FastAPI, HTTPException, Depends
145|from pydantic import BaseModel
146|from typing import Optional
147|
148|app = FastAPI(title="用户API")
149|
150|# Pydantic模型(类似Java的DTO)
151|class UserCreate(BaseModel):
152| name: str
153| age: int
154| email: Optional[str] = None
155|
156|class UserResponse(BaseModel):
157| id: int
158| name: str
159| age: int
160|
161|# 模拟数据库
162|users_db = {}
163|next_id = 0
164|
165|# 依赖注入(类似Spring的@Autowired)
166|def get_db():
167| return users_db
168|
169|# 路由
170|@app.post("/users", response_model=UserResponse)
171|async def create_user(user: UserCreate):
172| global next_id
173| next_id += 1
174| db = users_db
175| db[next_id] = {"id": next_id, **user.dict()}
176| return db[next_id]
177|
178|@app.get("/users/{user_id}", response_model=UserResponse)
179|async def get_user(user_id: int):
180| if user_id not in users_db:
181| raise HTTPException(status_code=404, detail="用户不存在")
182| return users_db[user_id]
183|
184|@app.get("/users")
185|async def list_users(skip: int = 0, limit: int = 10):
186| return list(users_db.values())[skip:skip+limit]
187|
188|# 运行: uvicorn main:app --reload
189|# 自动文档: http://localhost:8000/docs
190|
191|
192|### 异常处理
193|
194| 195|from fastapi import Request
196|from fastapi.responses import JSONResponse
197|
198|class AppError(Exception):
199| def init(self, code: int, message: str):
200| self.code = code
201| self.message = message
202|
203|@app.exception_handler(AppError)
204|async def app_error_handler(request: Request, exc: AppError):
205| return JSONResponse(
206| status_code=exc.code,
207| content={"error": exc.message}
208| )
209|
210|
211|### 数据库集成(SQLAlchemy)
212|
213| 214|from sqlalchemy import create_engine, Column, Integer, String
215|from sqlalchemy.ext.declarative import declarative_base
216|from sqlalchemy.orm import sessionmaker
217|
218|DATABASE_URL = "sqlite:///./app.db"
219|engine = create_engine(DATABASE_URL)
220|SessionLocal = sessionmaker(bind=engine)
221|Base = declarative_base()
222|
223|class UserModel(Base):
224| tablename = "users"
225| id = Column(Integer, primary_key=True)
226| name = Column(String)
227| age = Column(Integer)
228|
229|Base.metadata.create_all(bind=engine)
230|
231|# 依赖注入获取数据库会话
232|def get_db():
233| db = SessionLocal()
234| try:
235| yield db
236| finally:
237| db.close()
238|
239|@app.post("/users")
240|async def create_user(user: UserCreate, db = Depends(get_db)):
241| db_user = UserModel(name=user.name, age=user.age)
242| db.add(db_user)
243| db.commit()
244| db.refresh(db_user)
245| return db_user
246|
247|
248|## 四、项目结构
249|
250| 251|myproject/
252|├── pyproject.toml
253|├── README.md
254|├── src/
255|│ └── myproject/
256|│ ├── init.py
257|│ ├── main.py # FastAPI入口
258|│ ├── config.py # 配置
259|│ ├── models/
260|│ │ ├── init.py
261|│ │ ├── database.py # SQLAlchemy
262|│ │ └── user.py # ORM模型
263|│ ├── schemas/
264|│ │ ├── init.py
265|│ │ └── user.py # Pydantic模型
266|│ ├── routers/
267|│ │ ├── init.py
268|│ │ └── user.py # 路由
269|│ └── services/
270|│ ├── init.py
271|│ └── user.py # 业务逻辑
272|├── tests/
273|│ ├── init.py
274|│ └── test_users.py
275|├── Dockerfile
276|└── docker-compose.yml
277|
278|
279|## 五、测试
280|
281| 282|from fastapi.testclient import TestClient
283|from main import app
284|
285|client = TestClient(app)
286|
287|def test_create_user():
288| response = client.post("/users", json={"name": "张三", "age": 25})
289| assert response.status_code == 200
290| data = response.json()
291| assert data["name"] == "张三"
292|
293|def test_get_user_not_found():
294| response = client.get("/users/999")
295| assert response.status_code == 404
296|
297|
298|## 六、Docker部署
299|
300| 301|FROM python:3.12-slim
302|WORKDIR /app
303|COPY pyproject.toml .
304|RUN pip install -e .
305|COPY src/ src/
306|CMD ["uvicorn", "src.myproject.main:app", "--host", "0.0.0.0", "--port", "8000"]
307|
308|
309| 310|# docker-compose.yml
311|version: "3.8"
312|services:
313| api:
314| build: .
315| ports:
316| - "8000:8000"
317| environment:
318| - DATABASE_URL=sqlite:///./app.db
319| nginx:
320| image: nginx:latest
321| ports:
322| - "80:80"
323| volumes:
324| - ./nginx.conf:/etc/nginx/nginx.conf
325|
326|
327|## 七、性能优化
328|
329| 330|# 1. cProfile:性能分析
331|import cProfile
332|cProfile.run("my_function()")
333|
334|# 2. lru_cache:缓存
335|from functools import lru_cache
336|
337|@lru_cache(maxsize=256)
338|def expensive_computation(n):
339| return sum(i * i for i in range(n))
340|
341|# 3. NumPy:数值计算
342|import numpy as np
343|arr = np.arange(1000000)
344|result = arr ** 2 # 比纯Python快50倍
345|
346|# 4. 异步数据库
347|# pip install asyncpg # PostgreSQL
348|# pip install aiomysql # MySQL
349|
350|
351|## 八、Python能做什么?
352|
353|| 方向 | 工具 | 适合Java程序员吗? |
354||------|------|-------------------|
355|| Web开发 | Django/FastAPI/Flask | 非常适合 |
356|| 数据分析 | Pandas/NumPy/Matplotlib | 适合 |
357|| 机器学习 | PyTorch/TensorFlow | 需要学习 |
358|| 自动化 | 标准库 | 非常适合 |
359|| 爬虫 | Scrapy/requests | 适合 |
360|| DevOps | Ansible/Fabric | 适合 |
361|| 微服务 | FastAPI+Docker | 适合 |
362|
363|## 九、学习路径
364|
365| 366|第1周:语法基础(前3篇)
367|第2周:OOP+异常(第4-6篇)
368|第3周:并发+包管理(第7-8篇)
369|第4周:选方向深入
370| - Web开发: FastAPI官方教程
371| - 数据分析: Kaggle入门
372| - AI方向: fast.ai课程
373| - 自动化: 写脚本解决实际问题
374|
375|
376|## 写在最后
377|
378|Java和Python不是替代关系,而是互补关系。
379|
380|- Java:大型项目、企业级应用、高性能场景
381|- Python:快速开发、数据分析、AI、脚本工具
382|
383|很多公司都是Java做核心服务,Python做数据分析和自动化。两门都会,才是最强的。
384|
385|---
386|
387|本系列10篇完结。如果对你有帮助,关注我获取更多Python实战内容。