python &typescript 语法对照
一、类型
1# TS: let name: string = "hello"2name: str = "hello"3
4# TS: let count: number = 425count: int = 426
7# TS: let price: number = 3.148price: float = 3.149
10# TS: let items: string[] = ["a", "b"]11items: list[str] = ["a", "b"]12
13# TS: let data: Record<string, number> = {a: 1}14data: dict[str, int] = {"a": 1}15
7 collapsed lines
16# TS: let maybe: string | null = None17maybe: str | None = None18# 注意 Python 的 "None" 是 None(大写 N),不是 null19
20# TS: function add(a: number, b: number): number21def add(a: int, b: int) -> int:22 return a + b二、class + 构造器
class 新建时:
- ts 使用 class + construct
- python 使用 class + def __init__
class 使用时:
- ts 使用 new
- python 直接调用,像 function 一样,如()
1# TS:2# class User {3# constructor(public name: string, private age: number) {}4# }5
6class User:7 def __init__(self, name: str, age: int):8 self.name = name # 公开属性,相当于 public9 self._age = age # 带下划线 = 约定私有(private)10 self.__secret = "xxx" # 双下划线 = 名称装饰(真私有,但不常用)三、async/await - 两者一致
1# TS: async function fetchData(): Promise<string>2async def fetch_data() -> str:3 return "hello"4
5# TS: const data = await fetchData()6data = await fetch_data()7
8# TS: const stream = async function*() { yield "a" }9async def stream() -> AsyncGenerator[str, None]:10 yield "a"11 yield "b"四、类型联合
1# TS: let x: string | number = "hello"2x: str | int = "hello"3
4# TS: function greet(name?: string)5def greet(name: str | None = None):6 ...7
8# TS: const result = x ?? "default"9result = x or "default" # Python 用 or 代替 ??10# 或者更精确的条件判断:11result = "default" if x is None else xpython 中 None 不是 null,用 is 判断
1# ✅ 对的2if x is None: ...3
4# ❌ 不对(虽然能跑但不规范)5if x == None: ...五、try/except
python 中的 try/except 与 ts 中的 try/catch 基本一致
1# TS:2# try { risky() } catch (e) { handle(e) }3
4try:5 result = risky_function()6except ValueError as e:7 print(f"值错误: {e}")8except Exception as e:9 print(f"其他错误: {e}")10finally:11 cleanup()python 中抛出异常使用 raise ts 中抛出异常使用 throw
1raise ValueError("xxx") # TS: throw new Error("xxx")六、列表推导式
ts中的 map/filter,在 python 中使用列表推导式替代
1# TS: arr.map(x => x * 2)2result = [x * 2 for x in [1, 2, 3]]3# → [2, 4, 6]4
5# TS: arr.filter(x => x > 1)6result = [x for x in [1, 2, 3] if x > 1]7# → [2, 3]8
9# TS: arr.map(x => x * 2).filter(x => x > 2)10result = [x * 2 for x in [1, 2, 3] if x * 2 > 2]11# → [4, 6]12
13# 字典也同理:14result = {k: v for k, v in {"a": 1}.items() if v > 0}七、装饰器
1# @property = 让方法像属性一样调用2class User:3 def __init__(self, name: str):4 self._name = name5
6 @property # → user.name,不是 user.name()7 def name(self) -> str:8 return self._name9
10user = User("Alice")11print(user.name) # 不加括号在 python 中装饰器相当于高阶函数 @xxx 就相当于 xxx(func)
八、相对导入
1src/2 llm/3 provider.py4 ollama.py ← 这里想 import provider5 router.py1# 在 ollama.py 里:2from .provider import LLMProvider # 同目录下,用 .3# 相当于 TS: import { LLMProvider } from "./provider"4
5# 在 router.py 里:6from .ollama import OllamaProvider # 同目录下. 代表「当前包目录」,要用 . 就必须保证文件被当成模块运行(python -m src.llm.demo),不能直接 python ollama.py。
九、if name == “main”
1# 任何 Python 文件底部都可以写这个2if __name__ == "__main__":3 asyncio.run(main())只有用 python xxx.py 直接运行这个文件时才执行。被别的文件 import 时不执行。相当于 TS/JS 里检测 import.meta === 'main'或检查request.main === module
总结:TS 与 Python 关键字映射
| TS | Python |
|---|---|
let x: string | x: str |
null | None |
| === / !== | is / is not(用于 None) |
| ` | |
?? | or(近似) |
! | not |
const | 没有,不赋值就完事 |
throw | raise |
try/catch/finally | try/except/finally |
async function / async () => | async def |
yield* | yield from |
import { X } from "./y" | from .y import X |
class X { constructor() } | class X: def __init__(self) |
this | self(显式传参) |
new X() | X()(不需要 new) |