Python
js和Python的在语法的异同点
相同点(相似语法/功能)
| 功能 | JavaScript 示例 | Python 示例 |
|---|---|---|
| 变量定义(动态类型) | let x = 5; | x = 5 |
| 条件判断 | if (x > 0) {} | if x > 0: |
| 循环结构 | for (let i of arr) | for i in arr: |
| 函数定义 | function foo(a) {} | def foo(a): |
| 异常处理 | try { ... } catch(e) {} | try: ... except e: |
| 数组/列表支持 | [1, 2, 3] | [1, 2, 3] |
| 字典/对象 | { key: value } | { 'key': value } |
| 高阶函数(如 map/filter) | arr.map(fn) | map(fn, arr) |
不同点(语法风格/结构差异)
| 特性 | JavaScript | Python |
|---|---|---|
| 变量声明方式 | var, let, const | 无需关键字,直接赋值 |
| 代码块 | 使用 {} 包裹 | 使用缩进(强制) |
| 行末分号 | 可选但推荐 ; | 不使用分号 |
| 匿名函数 | () => {}(箭头函数) | lambda x: x + 1 |
| 字符串格式化 | `Hello ${name}`(模板字符串) | f"Hello {name}" |
| 类型转换 | Number("1"), String(123) | int("1"), str(123) |
| 类定义与继承 | class A extends B {} | class A(B): |
| 私有属性 | 无原生支持(常用 _name 或 #name) | 以 _ 或 __ 前缀标示私有 |
| 异步编程 | async/await 支持原生 Promise | async def, await,基于协程(asyncio) |
| null 与 undefined | 有 null 和 undefined 两种 | 统一使用 None |
| 真值判断 | false, 0, "", null, undefined, NaN 为假 | False, 0, "", None, [], {} 为假 |
使用案例对比
遍历列表/数组
js
const arr = [1, 2, 3];
for (let i of arr) {
console.log(i);
}py
arr = [1, 2, 3]
for i in arr:
print(i)函数定义和调用
js
function add(a, b) {
return a + b;
}
add(1, 2);py
def add(a, b):
return a + b
add(1, 2)异步编程对比
| 特性 | JavaScript | Python |
|---|---|---|
| 异步语法 | async function, await | async def, await |
| 核心机制 | 基于事件循环 + Promise | 基于协程(asyncio) |
| 内置 Promise 支持 | 有原生 Promise 类型 | 通过 asyncio.Future 等实现 |
| 并发库 | Promise, setTimeout, fetch, RxJS | asyncio, concurrent.futures, threading |
js
// JavaScript
async function fetchData() {
const res = await fetch('https://api.example.com');
const data = await res.json();
console.log(data);
}py
# Python
import aiohttp
import asyncio
async def fetch_data():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.example.com') as resp:
data = await resp.json()
print(data)
# asyncio.run(fetch_data())模块系统对比
| 特性 | JavaScript | Python |
|---|---|---|
| 导入语法 | import { func } from './module.js' | from module import func |
| 默认导出 | export default | 无默认导出概念 |
| 包管理工具 | npm, yarn, pnpm | pip, poetry, pipenv |
| 模块类型 | CommonJS (require), ESModules (import) | .py 文件就是模块,支持包结构(__init__.py) |
类与对象对比
| 特性 | JavaScript | Python |
|---|---|---|
| 类定义语法 | class A {} | class A: |
| 构造函数 | constructor() | __init__() |
| 继承 | class B extends A {} | class B(A): |
| 私有属性 | #name(ES2022+)或 _name(习惯) | _name(保护)、__name(私有) |
| 方法绑定 | 需要手动绑定 this(或使用箭头函数) | self 自动传递 |
js
// JavaScript
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}py
# Python
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}")其他语言特性对比
| 特性 | JavaScript | Python |
|---|---|---|
| 函数是一等公民 | 是 | 是 |
| 正则表达式内置支持 | 是 | 是(通过 re 模块) |
| JSON 处理 | JSON.stringify / JSON.parse | json.dumps / json.loads |
| 默认参数 | function fn(a = 1) | def fn(a=1) |
| 函数重载 | 不支持(需手动处理参数) | 不支持传统重载,可用装饰器模拟 |
| 枚举 | 需手动实现或用 TS | Enum 模块原生支持 |