Python 基础Technical Deep Dive
Python 快速入门:JavaScript 开发者指南
发布时间2025/11/05
分类Python 基础
预计阅读8 分钟
作者吴长龙
*
本文面向有 JavaScript 基础的开发者,介绍 Python 语法、数据类型、函数、类与异步编程,让你快速上手 Python。
01.内容
# Python 快速入门:JavaScript 开发者指南
作为 JavaScript 开发者,你已经具备编程思维,只需要了解 Python 的语法差异即可快速上手。
02.1. 变量与数据类型
1.1 变量声明
python snippetpython
# Python 使用 = 赋值,没有 let/const/var
name = "小明" # 字符串
age = 25 # 整数
price = 19.99 # 浮点数
is_active = True # 布尔值 (首字母大写)
# 常量约定:全大写
MAX_SIZE = 100
# 多变量赋值
x, y, z = 1, 2, 3对比 JavaScript:
javascript snippetjavascript
// JS
const name = "小明";
let age = 25;
var is_active = true;1.2 基本数据类型
python snippetpython
# 字符串
s = "Hello"
s = 'Hello'
s = """多行
字符串""" # 类似 JS 的 template literal
# 数字
int_num = 42 # 整数
float_num = 3.14 # 浮点数
complex_num = 3+4j # 复数
# 布尔值
is_python_cool = True # 注意首字母大写
is_js_better = False
# None (类似 JS 的 null)
result = None1.3 数据类型转换
python snippetpython
# 字符串转数字
int("42") # 42
float("3.14") # 3.14
# 数字转字符串
str(42) # "42"
# 字符串转布尔值
bool("") # False (空字符串为 False)
bool("hello") # True (非空字符串为 True)
bool(0) # False
bool(1) # True03.2. 数据结构
2.1 列表 (List) - 类似 JS 数组
python snippetpython
# 创建列表
fruits = ["apple", "banana", "orange"]
# 访问元素 (0 索引)
fruits[0] # "apple"
fruits[-1] # "orange" (倒数第一个)
# 切片操作 (类似 JS 的 slice)
fruits[1:3] # ["banana", "orange"]
fruits[:2] # ["apple", "banana"]
fruits[::2] # ["apple", "orange"] (步长2)
# 修改列表
fruits.append("grape") # 末尾添加
fruits.insert(1, "mango") # 插入
fruits.remove("apple") # 删除
fruits.pop() # 弹出末尾
# 列表推导式 (Python 特色)
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]2.2 元组 (Tuple) - 不可变列表
python snippetpython
# 元组创建
point = (10, 20)
colors = ("red", "green", "blue")
# 解包 (类似 JS 解构)
x, y = point # x=10, y=20
# 元组不可修改,但可以重新赋值
# point[0] = 15 # 报错!2.3 字典 (Dict) - 类似 JS 对象
python snippetpython
# 创建字典
user = {
"name": "小明",
"age": 25,
"is_active": True
}
# 访问值
user["name"] # "小明"
user.get("email", "default@example.com") # 类似 || 操作符
# 修改字典
user["age"] = 26 # 修改
user["email"] = "x@com" # 添加
del user["age"] # 删除
user.pop("is_active") # 弹出删除
# 字典推导式
names = ["alice", "bob", "charlie"]
name_lengths = {name: len(name) for name in names}
# {"alice": 5, "bob": 3, "charlie": 8}2.4 集合 (Set) - 类似 JS Set
python snippetpython
# 创建集合
fruits = {"apple", "banana", "orange"}
# 操作
fruits.add("grape") # 添加
fruits.remove("apple") # 删除
fruits.pop() # 随机弹出一个
# 集合运算
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1 | set2 # 并集: {1, 2, 3, 4}
set1 & set2 # 交集: {2, 3}
set1 - set2 # 差集: {1}04.3. 控制流
3.1 条件判断
python snippetpython
age = 18
if age >= 18:
print("成年人")
elif age >= 13:
print("青少年")
else:
print("儿童")
# 三元表达式 (类似 JS 的 ?:)
status = "成年" if age >= 18 else "未成年"3.2 循环
python snippetpython
# for 循环 (类似 JS for...of)
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# range (类似 JS 的 for 循环)
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# 遍历字典
user = {"name": "小明", "age": 25}
for key, value in user.items():
print(f"{key}: {value}")
# 列表推导式代替 map/filter
numbers = [1, 2, 3, 4, 5]
# map
doubled = [x * 2 for x in numbers] # [2, 4, 6, 8, 10]
# filter
evens = [x for x in numbers if x % 2 == 0] # [2, 4]3.3 match 语句 (Python 3.10+)
python snippetpython
# 类似 JS switch,但更强大
status = "pending"
match status:
case "pending":
print("待处理")
case "success":
print("成功")
case "error":
print("错误")
case _:
print("未知状态") # default05.4. 函数
4.1 基本函数定义
python snippetpython
# 定义函数 (类似 JS 函数声明)
def greet(name):
return f"Hello, {name}!"
# 调用
result = greet("小明") # "Hello, 小明!"
# 默认参数 (类似 JS)
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("小明") # "Hello, 小明!"
greet("小明", "Hi") # "Hi, 小明!"4.2 多返回值
python snippetpython
# 返回多个值 (实际返回元组)
def get_user():
return "小明", 25, "北京"
name, age, city = get_user() # 解包4.3 *args 和 **kwargs
python snippetpython
# *args 可变位置参数 (类似 JS 的 rest 参数)
def sum(*args):
total = 0
for num in args:
total += num
return total
sum(1, 2, 3, 4) # 10
# **kwargs 可变关键字参数
def configure(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
configure(host="localhost", port=8080)
# host: localhost
# port: 80804.4 匿名函数
python snippetpython
# lambda (类似 JS 箭头函数)
add = lambda x, y: x + y
add(1, 2) # 3
# 结合内置函数
numbers = [1, 2, 3, 4, 5]
sorted(numbers, key=lambda x: -x) # [5, 4, 3, 2, 1]06.5. 类与面向对象
5.1 类定义
python snippetpython
class User:
# 类属性
species = "Human"
# 构造方法 (类似 JS constructor)
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
# 实例方法 (self 类似 JS 的 this)
def greet(self):
return f"Hello, I'm {self.name}"
# 类方法
@classmethod
def create_anonymous(cls):
return cls("Anonymous", 0)
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建实例
user = User("小明", 25)
user.greet() # "Hello, I'm 小明"
User.is_adult(18) # True5.2 继承
python snippetpython
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
dog = Dog("旺财")
dog.speak() # "旺财 says woof!"5.3 数据类 (Python 3.7+)
python snippetpython
# @dataclass 自动生成 __init__, __repr__ 等
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
email: str = "default@example.com" # 默认值
user = User("小明", 25)
print(user) # User(name='小明', age=25, email='default@example.com')07.6. 异步编程
6.1 async/await
python snippetpython
import asyncio
# 定义异步函数 (类似 JS async function)
async def fetch_data():
print("开始获取数据...")
await asyncio.sleep(1) # 模拟异步操作
print("数据获取完成!")
return {"data": "hello"}
# 运行异步函数
async def main():
result = await fetch_data()
print(result)
# 方式1: asyncio.run (推荐)
asyncio.run(main())
# 方式2: 在已有事件循环中
# await fetch_data()6.2 并发执行
python snippetpython
import asyncio
async def task1():
await asyncio.sleep(1)
return "任务1完成"
async def task2():
await asyncio.sleep(2)
return "任务2完成"
async def main():
# 并发执行 (类似 Promise.all)
results = await asyncio.gather(task1(), task2())
print(results) # ["任务1完成", "任务2完成"]
asyncio.run(main())6.3 异步生成器
python snippetpython
async def async_generator():
for i in range(3):
await asyncio.sleep(0.5)
yield i
async def main():
async for value in async_generator():
print(value)
asyncio.run(main())08.7. 模块与包
7.1 导入
python snippetpython
# 导入整个模块
import math
math.sqrt(16) # 4.0
# 导入特定函数
from math import sqrt, pi
sqrt(16) # 4.0
# 重命名
import numpy as np
np.array([1, 2, 3])
# 导入所有 (不推荐)
# from math import *7.2 创建模块
python snippetpython
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# 同一目录下使用
import mymodule
mymodule.greet("小明")7.3 pip 包管理
bash snippetbash
# 安装包
pip install requests
# requirements.txt
# requests==2.28.0
# numpy>=1.21.0
# 安装依赖
pip install -r requirements.txt09.8. 常用内置函数
| 函数 | 说明 | 类似 JS |
|---|---|---|
len() | 长度 | .length |
range() | 数字序列 | for 循环 |
enumerate() | 带索引遍历 | .entries() |
zip() | 合并多个列表 | 无 |
map() | 映射 | .map() |
filter() | 过滤 | .filter() |
sum() | 求和 | 无 |
min()/max() | 最小/最大值 | Math.min/max |
sorted() | 排序 | .sort() |
isinstance() | 类型检查 | instanceof |
10.9. 错误处理
python snippetpython
# try-except (类似 try-catch)
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以0!")
except Exception as e:
print(f"其他错误: {e}")
else:
print("没有错误")
finally:
print("总是执行")
# 抛出异常 (类似 throw)
raise ValueError("无效的值")11.10. 类型提示 (Type Hints)
python snippetpython
# 类型标注 (类似 TypeScript)
def greet(name: str) -> str:
return f"Hello, {name}!"
# 复杂类型
from typing import List, Dict, Optional, Union
def process_items(items: List[int]) -> Dict[str, int]:
return {
"sum": sum(items),
"count": len(items)
}
# Optional 类似 union with null
def get_name(user_id: int) -> Optional[str]:
if user_id > 0:
return "小明"
return None
# Union 类似 union 类型
def parse(value: Union[str, int]) -> str:
return str(value)12.总结
| JavaScript | Python |
|---|---|
let/const/var | 无关键字,直接赋值 |
function | def |
arrow => | lambda |
this | self |
class | class (类似) |
async/await | async/await |
null | None |
undefined | 抛异常 |
template literal | f-string |
...rest | *args, **kwargs |
Python 和 JavaScript 非常相似,你只需要记住几个关键差异就能快速上手。下一篇文章我们将介绍 Python 异步编程详解,深入理解 asyncio。