Python 语法速成指南:前端开发者视角(JS 类比版)

0 阅读6分钟

学习 Agent 开发一段时间了,发现 Python 语法其实和 JavaScript 很像。

这篇文章帮你快速理解项目中用到的所有 Python 语法,用 JavaScript 类比,一看就懂

应该先发出来这个的。。。。现在才补

1bd40ca3-8888-4444-9c17-1efd6aed8ae4.png


一、基础语法对比

1.1 变量定义

PythonJavaScript
name = "cat"let name = "cat"
count = 10let count = 10
不需要声明类型需要 let/const/var

Python 不需要声明变量类型,直接赋值就行

# Python
name = "cat"
count = 10
is_correct = True  # 注意:True 不是 true
// JavaScript
let name = "cat";
let count = 10;
let isCorrect = true;

1.2 字符串

PythonJavaScript
f-string 格式化模板字符串
"Hello {name}"不支持
f"Hello {name}"`Hello ${name}`
# Python f-string(项目里大量使用)
word = "cat"
cn = "猫"
prompt = f"请讲解单词 '{word}'(意思是'{cn}')"
# 结果:请讲解单词 'cat'(意思是'猫')
// JavaScript 模板字符串
let word = "cat";
let cn = "猫";
let prompt = `请讲解单词 '${word}'(意思是'${cn}')`;

1.3 列表(数组)

PythonJavaScript
listArray
[1, 2, 3][1, 2, 3]
words.append("dog")words.push("dog")
words[0]words[0]
len(words)words.length
# Python
words = ["cat", "dog", "bird"]
words.append("fish")      # 添加元素
first = words[0]          # 取第一个
count = len(words)        # 获取长度
last = words[-1]          # 取最后一个(JS没有这个!)
// JavaScript
let words = ["cat", "dog", "bird"];
words.push("fish");       // 添加元素
let first = words[0];     // 取第一个
let count = words.length; // 获取长度
let last = words[words.length - 1]; // 取最后一个

1.4 字典(对象)

PythonJavaScript
dictObject
{"key": "value"}{"key": "value"}
data["key"]data.keydata["key"]
data.get("key")data.key
# Python
word = {"en": "cat", "cn": "猫"}
en = word["en"]           # 取值
cn = word.get("cn")       # 取值(不存在返回 None)
word["phonetic"] = "kat"  # 添加属性
// JavaScript
let word = {en: "cat", cn: "猫"};
let en = word.en;          // 取值
let cn = word["cn"];       // 取值(不存在返回 undefined)
word.phonetic = "kat";     // 添加属性

1.5 None vs null

PythonJavaScript
Nonenull / undefined
if value is None:if (value === null)
# Python
result = None
if result is None:
    print("没有结果")
// JavaScript
let result = null;
if (result === null) {
    console.log("没有结果");
}

二、函数对比

2.1 定义函数

PythonJavaScript
def func():function func()
无需 return 类型无需 return 类型
# Python
def learn_word(word):
    """学习一个单词"""  # 这是文档字符串
    return f"学习 {word}"

# 调用
result = learn_word("cat")
// JavaScript
function learnWord(word) {
    return `学习 ${word}`;
}

// 调用
let result = learnWord("cat");

2.2 参数解包(项目中大量使用)

# Python 字典解包(**arguments)
arguments = {"word": "cat", "cn": "猫"}

# 这两种写法等价:
learn_word(**arguments)    # 解包后变成 learn_word(word="cat", cn="猫")
learn_word(word="cat", cn="猫")  # 直接传参数
// JavaScript 对象解包(...arguments)
let arguments = {word: "cat", cn: "猫"};

// 这两种写法等价:
learnWord(...Object.values(arguments)); // JS 不能直接这样用
learnWord(arguments.word, arguments.cn); // 手动传参数

Python 的 **dict 可以直接把字典变成函数参数,JS 没有这个特性


2.3 Lambda(匿名函数)

PythonJavaScript
lambda x: x * 2x => x * 2
# Python lambda(简单匿名函数)
double = lambda x: x * 2
result = double(5)  # 10
// JavaScript 箭头函数
let double = x => x * 2;
let result = double(5); // 10

三、流程控制对比

3.1 条件判断

PythonJavaScript
if/elif/elseif/else if/else
and / or / not&& / ! / ||
# Python
score = 85
if score >= 90:
    print("优秀")
elif score >= 60:
    print("及格")
else:
    print("不及格")

# 逻辑运算
if score >= 60 and score < 90:
    print("中等")
// JavaScript
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 循环

PythonJavaScript
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)
# Python for 循环
words = ["cat", "dog", "bird"]
for word in words:
    print(word)

# Python range 循环
for i in range(3):
    print(i)  # 0, 1, 2

# Python while 循环
count = 0
while count < 3:
    print(count)
    count += 1
// JavaScript for...of 循环
let words = ["cat", "dog", "bird"];
for (let word of words) {
    console.log(word);
}

// JavaScript for 循环
for (let i = 0; i < 3; i++) {
    console.log(i);
}

// JavaScript while 循环
let count = 0;
while (count < 3) {
    console.log(count);
    count++;
}

3.3 列表推导式(Python 特色)

感觉一行代码说了一段话~~

# Python 列表推导式(一行代码创建新列表)
words = ["cat", "dog", "bird"]
upper_words = [w.upper() for w in words]  # ["CAT", "DOG", "BIRD"]

# 带条件过滤
long_words = [w for w in words if len(w) > 3]  # ["bird"]

# 项目中用到的例子:从错题本移除单词
user_memory["wrong_words"] = [
    w for w in user_memory["wrong_words"] if w["en"] != en
]
// JavaScript 用 map/filter 实现
let words = ["cat", "dog", "bird"];
let upperWords = words.map(w => w.toUpperCase()); // ["CAT", "DOG", "BIRD"]

// 带条件过滤
let longWords = words.filter(w => w.length > 3); // ["bird"]

// 从错题本移除单词
userMemory.wrongWords = userMemory.wrongWords.filter(w => w.en !== en);

四、模块导入对比

PythonJavaScript
import moduleimport module
from module import funcimport { func } from module
import module as mimport * as m from module
# Python 导入
import requests                           # 导入整个模块
from flask import Flask, request          # 导入部分
import json
from datetime import datetime
// JavaScript 导入
import requests from 'requests';          // 导入整个模块
import { Flask, request } from 'flask';   // 导入部分(ES6)
import * as json from 'json';

五、异步/并发对比

这是最大的区别!Python 默认同步,JS 默认异步,这个思路一点要转变

5.1 HTTP 请求

# Python requests(同步,会阻塞)
import requests

response = requests.post(url, headers=headers, json=data)
# 等待响应完成,然后继续
result = response.json()
// JavaScript fetch(异步,Promise)
const response = await fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
});
const result = await response.json();

// 或者用 Promise
fetch(url, options).then(res => res.json()).then(data => {
    console.log(data);
});

5.2 流式响应(项目中大量使用)

# Python 流式处理
response = requests.post(url, stream=True)  # stream=True 开启流式

for line in response.iter_lines():
    if line:
        chunk = json.loads(line)
        content = chunk["choices"][0]["delta"]["content"]
        print(content)
// JavaScript 流式处理(Fetch API)
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 请求库

PythonJavaScript
requestsfetch / axios
requests.post()fetch()axios.post()
# Python requests
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()
// JavaScript fetch
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();
}

// JavaScript axios
const result = await axios.post("https://api.example.com/chat", {
    model: "glm-5",
    messages: [...]
}, {
    headers: { Authorization: "Bearer xxx" }
});

6.2 JSON 处理

PythonJavaScript
json.loads()JSON.parse()
json.dumps()JSON.stringify()
# Python JSON
import json

# 解析 JSON 字符串
data = json.loads('{"name": "cat"}')  # 变成字典

# 转成 JSON 字符串
json_str = json.dumps(data, ensure_ascii=False)  # 中文不转义
// JavaScript JSON
// 解析 JSON 字符串
let data = JSON.parse('{"name": "cat"}');  // 变成对象

// 转成 JSON 字符串
let jsonStr = JSON.stringify(data);

6.3 文件操作

PythonJavaScript
open()fs.readFileSync()
with open()Node.js 没有
# Python 文件操作(项目中用来保存用户数据)
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)

# with 语句会自动关闭文件,不需要手动 close()
// Node.js 文件操作
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 创建应用

# Python Flask
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)
// JavaScript Express
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 路由装饰器

# Python Flask 装饰器(@app.route)
@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}
// JavaScript Express 路由
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 流式响应

# Python Flask 流式响应(SSE)
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")
// JavaScript Express 流式响应
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();

八、异常处理

# Python try/except
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}")
// JavaScript try/catch
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

# Function Calling 中用到的
tool_call["function"]["arguments"] = '{"word": "cat"}'
arguments = json.loads(tool_call["function"]["arguments"])
# 得到:{"word": "cat"}

# 用 **arguments 解包,自动匹配函数参数
result = learn_word(**arguments)
# 相当于:learn_word(word="cat")

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 生成器

# Flask 流式响应中用到
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一块数据
    
    yield "data: [DONE]\n\n"

# yield 是"暂停并返回",下次调用继续从这里开始

9.4 global 关键字

# 项目中修改全局变量
messages = []

def clear():
    global messages  # 声明使用全局变量
    messages.clear()  # 否则会创建新的局部变量

9.5 编码处理

# 文件开头声明编码
# -*- coding: utf-8 -*-

# 命令行输出中文
import sys
sys.stdout.reconfigure(encoding='utf-8')

# 读取/写入文件时指定编码
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

十、速查表

PythonJavaScript说明
True/Falsetrue/false布尔值
Nonenull/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/elseif/else if/else条件
def func():function func()函数定义
lambda x: x*2x => x*2匿名函数
json.loads()JSON.parse()解析JSON
json.dumps()JSON.stringify()转JSON
try/excepttry/catch异常处理
import ximport x导入
with open()文件操作
**dict字典解包
[x for x in list]list.map()列表推导
yield生成器

写给前端开发者的 Python 速成指南,用 JS 类比,一看就懂