学习 Agent 开发一段时间了,发现 Python 语法其实和 JavaScript 很像。
这篇文章帮你快速理解项目中用到的所有 Python 语法,用 JavaScript 类比,一看就懂。
应该先发出来这个的。。。。现在才补

一、基础语法对比
1.1 变量定义
| Python | JavaScript |
|---|
name = "cat" | let name = "cat" |
count = 10 | let count = 10 |
| 不需要声明类型 | 需要 let/const/var |
Python 不需要声明变量类型,直接赋值就行。
name = "cat"
count = 10
is_correct = True
let name = "cat";
let count = 10;
let isCorrect = true;
1.2 字符串
| Python | JavaScript |
|---|
| f-string 格式化 | 模板字符串 |
"Hello {name}" | 不支持 |
f"Hello {name}" | `Hello ${name}` |
word = "cat"
cn = "猫"
prompt = f"请讲解单词 '{word}'(意思是'{cn}')"
let word = "cat";
let cn = "猫";
let prompt = `请讲解单词 '${word}'(意思是'${cn}')`;
1.3 列表(数组)
| Python | JavaScript |
|---|
list | Array |
[1, 2, 3] | [1, 2, 3] |
words.append("dog") | words.push("dog") |
words[0] | words[0] |
len(words) | words.length |
words = ["cat", "dog", "bird"]
words.append("fish")
first = words[0]
count = len(words)
last = words[-1]
let words = ["cat", "dog", "bird"];
words.push("fish");
let first = words[0];
let count = words.length;
let last = words[words.length - 1];
1.4 字典(对象)
| Python | JavaScript |
|---|
dict | Object |
{"key": "value"} | {"key": "value"} |
data["key"] | data.key 或 data["key"] |
data.get("key") | data.key |
word = {"en": "cat", "cn": "猫"}
en = word["en"]
cn = word.get("cn")
word["phonetic"] = "kat"
let word = {en: "cat", cn: "猫"};
let en = word.en;
let cn = word["cn"];
word.phonetic = "kat";
1.5 None vs null
| Python | JavaScript |
|---|
None | null / undefined |
if value is None: | if (value === null) |
result = None
if result is None:
print("没有结果")
let result = null;
if (result === null) {
console.log("没有结果");
}
二、函数对比
2.1 定义函数
| Python | JavaScript |
|---|
def func(): | function func() |
| 无需 return 类型 | 无需 return 类型 |
def learn_word(word):
"""学习一个单词"""
return f"学习 {word}"
result = learn_word("cat")
function learnWord(word) {
return `学习 ${word}`;
}
let result = learnWord("cat");
2.2 参数解包(项目中大量使用)
arguments = {"word": "cat", "cn": "猫"}
learn_word(**arguments)
learn_word(word="cat", cn="猫")
let arguments = {word: "cat", cn: "猫"};
learnWord(...Object.values(arguments));
learnWord(arguments.word, arguments.cn);
Python 的 **dict 可以直接把字典变成函数参数,JS 没有这个特性。
2.3 Lambda(匿名函数)
| Python | JavaScript |
|---|
lambda x: x * 2 | x => x * 2 |
double = lambda x: x * 2
result = double(5)
let double = x => x * 2;
let result = double(5);
三、流程控制对比
3.1 条件判断
| Python | JavaScript |
|---|
if/elif/else | if/else if/else |
and / or / not | && / ! / || |
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
if score >= 60 and score < 90:
print("中等")
let score = 85;
if (score >= 90) {
console.log("优秀");
} else if (score >= 60) {
console.log("及格");
} else {
console.log("不及格");
}
if (score >= 60 && score < 90) {
console.log("中等");
}
3.2 循环
| Python | JavaScript |
|---|
for item in list: | for (let item of list) |
for i in range(10): | for (let i = 0; i < 10; i++) |
while condition: | while (condition) |
words = ["cat", "dog", "bird"]
for word in words:
print(word)
for i in range(3):
print(i)
count = 0
while count < 3:
print(count)
count += 1
let words = ["cat", "dog", "bird"];
for (let word of words) {
console.log(word);
}
for (let i = 0; i < 3; i++) {
console.log(i);
}
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
3.3 列表推导式(Python 特色)
感觉一行代码说了一段话~~
words = ["cat", "dog", "bird"]
upper_words = [w.upper() for w in words]
long_words = [w for w in words if len(w) > 3]
user_memory["wrong_words"] = [
w for w in user_memory["wrong_words"] if w["en"] != en
]
let words = ["cat", "dog", "bird"];
let upperWords = words.map(w => w.toUpperCase());
let longWords = words.filter(w => w.length > 3);
userMemory.wrongWords = userMemory.wrongWords.filter(w => w.en !== en);
四、模块导入对比
| Python | JavaScript |
|---|
import module | import module |
from module import func | import { func } from module |
import module as m | import * as m from module |
import requests
from flask import Flask, request
import json
from datetime import datetime
import requests from 'requests';
import { Flask, request } from 'flask';
import * as json from 'json';
五、异步/并发对比
这是最大的区别!Python 默认同步,JS 默认异步,这个思路一点要转变。
5.1 HTTP 请求
import requests
response = requests.post(url, headers=headers, json=data)
result = response.json()
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
});
const result = await response.json();
fetch(url, options).then(res => res.json()).then(data => {
console.log(data);
});
5.2 流式响应(项目中大量使用)
response = requests.post(url, stream=True)
for line in response.iter_lines():
if line:
chunk = json.loads(line)
content = chunk["choices"][0]["delta"]["content"]
print(content)
const response = await fetch(url, options);
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const data = JSON.parse(chunk);
console.log(data);
}
六、常用库对比
6.1 HTTP 请求库
| Python | JavaScript |
|---|
requests | fetch / axios |
requests.post() | fetch() 或 axios.post() |
import requests
response = requests.post(
"https://api.example.com/chat",
headers={"Authorization": "Bearer xxx"},
json={"model": "glm-5", "messages": [...]}
)
if response.status_code == 200:
result = response.json()
const response = await fetch("https://api.example.com/chat", {
method: "POST",
headers: { Authorization: "Bearer xxx" },
body: JSON.stringify({ model: "glm-5", messages: [...] })
});
if (response.ok) {
const result = await response.json();
}
const result = await axios.post("https://api.example.com/chat", {
model: "glm-5",
messages: [...]
}, {
headers: { Authorization: "Bearer xxx" }
});
6.2 JSON 处理
| Python | JavaScript |
|---|
json.loads() | JSON.parse() |
json.dumps() | JSON.stringify() |
import json
data = json.loads('{"name": "cat"}')
json_str = json.dumps(data, ensure_ascii=False)
let data = JSON.parse('{"name": "cat"}');
let jsonStr = JSON.stringify(data);
6.3 文件操作
| Python | JavaScript |
|---|
open() | fs.readFileSync() |
with open() | Node.js 没有 |
import json
with open("user_memory.json", "r", encoding="utf-8") as f:
data = json.load(f)
with open("user_memory.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('user_memory.json', 'utf8'));
fs.writeFileSync('user_memory.json', JSON.stringify(data, null, 2));
七、Flask vs Express
7.1 创建应用
from flask import Flask, request, Response, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/chat", methods=["POST"])
def chat():
user_input = request.json.get("message", "")
return {"reply": "Hello"}
if __name__ == "__main__":
app.run(debug=True, port=5000)
import express from 'express';
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.sendFile("index.html");
});
app.post("/chat", (req, res) => {
const userInput = req.body.message || "";
res.json({ reply: "Hello" });
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
7.2 路由装饰器
@app.route("/points", methods=["GET"])
def get_points():
return {"points": 100}
@app.route("/points/add", methods=["POST"])
def add_points():
action = request.json.get("action")
return {"added": 10}
app.get("/points", (req, res) => {
res.json({ points: 100 });
});
app.post("/points/add", (req, res) => {
const action = req.body.action;
res.json({ added: 10 });
});
7.3 流式响应
def generate():
for i in range(5):
yield f"data: {i}\n\n"
yield "data: [DONE]\n\n"
return Response(generate(), mimetype="text/event-stream")
res.setHeader('Content-Type', 'text/event-stream');
for (let i = 0; i < 5; i++) {
res.write(`data: ${i}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();
八、异常处理
try:
response = requests.post(url, json=data, timeout=30)
result = response.json()
except requests.exceptions.RequestException as e:
print(f"网络错误: {e}")
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data)
});
const result = await response.json();
} catch (e) {
console.log(`错误: ${e}`);
}
九、项目中实际用到的代码解析
9.1 字典解包 **arguments
tool_call["function"]["arguments"] = '{"word": "cat"}'
arguments = json.loads(tool_call["function"]["arguments"])
result = learn_word(**arguments)
9.2 列表推导式
user_memory["wrong_words"] = [
w for w in user_memory["wrong_words"] if w["en"] != en
]
new_list = []
for w in user_memory["wrong_words"]:
if w["en"] != en:
new_list.append(w)
user_memory["wrong_words"] = new_list
9.3 yield 生成器
def generate():
full_reply = ""
for line in response.iter_lines():
if line:
content = parse_content(line)
full_reply += content
yield f"data: {content}\n\n"
yield "data: [DONE]\n\n"
9.4 global 关键字
messages = []
def clear():
global messages
messages.clear()
9.5 编码处理
import sys
sys.stdout.reconfigure(encoding='utf-8')
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
十、速查表
| Python | JavaScript | 说明 |
|---|
True/False | true/false | 布尔值 |
None | null/undefined | 空值 |
and/or/not | &&/||/\! | 逻辑运算 |
len(x) | x.length | 长度 |
list.append() | array.push() | 添加元素 |
dict["key"] | obj.key | 取值 |
f"{var}" | `${var}` | 字符串格式化 |
for x in list: | for (let x of list) | 循环 |
if/elif/else | if/else if/else | 条件 |
def func(): | function func() | 函数定义 |
lambda x: x*2 | x => x*2 | 匿名函数 |
json.loads() | JSON.parse() | 解析JSON |
json.dumps() | JSON.stringify() | 转JSON |
try/except | try/catch | 异常处理 |
import x | import x | 导入 |
with open() | 无 | 文件操作 |
**dict | 无 | 字典解包 |
[x for x in list] | list.map() | 列表推导 |
yield | 无 | 生成器 |
写给前端开发者的 Python 速成指南,用 JS 类比,一看就懂