一、基础语法
1. 变量和数据类型
```python
变量(动态类型)
name = "张三" # 字符串
age = 25 # 整数
price = 99.99 # 浮点数
is_active = True # 布尔值
nothing = None # 空值
类型检查
type(name) # <class 'str'>
isinstance(age, int) # True
类型转换
str(25) # "25"
int("100") # 100
float("3.14") # 3.14
bool(1) # True
```
2. 字符串操作
```python
字符串创建
s1 = '单引号'
s2 = "双引号"
s3 = """多行
字符串"""
s4 = r"原始字符串\n不转义"
f-string (Python 3.6+)
name = "张三"
age = 25
msg = f"{name}今年{age}岁"
字符串方法
text = " Hello, Python! "
text.strip() # "Hello, Python!" 去除两端空格
text.lower() # " hello, python! "
text.upper() # " HELLO, PYTHON! "
text.startswith(" ") # True
text.endswith("! ") # True
text.replace("Hello", "Hi") # " Hi, Python! "
text.split(",") # [' Hello', ' Python! ']
",".join(['a', 'b']) # "a,b"
字符串格式化
"{}今年{}岁".format(name, age) # 旧方式
"%s今年%d岁" % (name, age) # 更旧方式
```
3. 数字和运算
```python
算术运算
x = 10
y = 3
x + y # 13 加
x - y # 7 减
x * y # 30 乘
x / y # 3.333... 除(浮点数)
x // y # 3 整除
x % y # 1 取模
x ** y # 1000 幂
-x # -10 负
赋值运算符
x += 5 # x = x + 5
x -= 2 # x = x - 2
x *= 3 # x = x * 3
x /= 2 # x = x / 2
x //= 3 # x = x // 3
比较运算
x == y # False 等于
x != y # True 不等于
x > y # True 大于
x < y # False 小于
x >= y # True 大于等于
x <= y # False 小于等于
逻辑运算
True and False # False
True or False # True
not True # False
```
二、数据结构
1. 列表(List)
```python
创建列表
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
nested = [[1, 2], [3, 4]]
访问元素
numbers[0] # 1 第一个元素
numbers[-1] # 5 最后一个元素
numbers[1:3] # [2, 3] 切片
numbers[::2] # [1, 3, 5] 步长2
修改列表
numbers.append(6) # [1, 2, 3, 4, 5, 6] 添加
numbers.insert(2, 99)# [1, 2, 99, 3, 4, 5, 6] 插入
numbers[0] = 100 # [100, 2, 99, 3, 4, 5, 6] 修改
del numbers[1] # [100, 99, 3, 4, 5, 6] 删除
numbers.pop() # 移除并返回最后一个元素 (6)
numbers.remove(99) # [100, 3, 4, 5] 移除第一个匹配项
列表方法
numbers.sort() # 排序(原地)
sorted(numbers) # 返回新排序列表
numbers.reverse() # 反转
numbers.copy() # 浅拷贝
numbers.count(3) # 计数
numbers.index(3) # 查找索引
列表推导式
squares = [x**2 for x in range(10)] # [0, 1, 4, ..., 81]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
```
2. 元组(Tuple)
```python
创建元组(不可变)
point = (10, 20)
single = (5,) # 单元素元组需要逗号
empty = () # 空元组
访问元素
x, y = point # 解包: x=10, y=20
x = point[0] # 10
y = point[1] # 20
命名元组
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
p.x # 10
p.y # 20
```
3. 字典(Dict)
```python
创建字典
person = {"name": "张三", "age": 25}
person2 = dict(name="李四", age=30)
访问元素
person["name"] # "张三"
person.get("age") # 25
person.get("gender", "男") # "男"(默认值)
修改字典
person["age"] = 26 # 修改
person["city"] = "北京" # 添加
person.update({"age": 27, "job": "工程师"}) # 批量更新
del person["city"] # 删除
value = person.pop("job") # 移除并返回值
字典方法
person.keys() # 所有键
person.values() # 所有值
person.items() # 所有键值对
person.copy() # 浅拷贝
person.clear() # 清空
字典推导式
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, ..., 4: 16}
```
4. 集合(Set)
```python
创建集合(无序、不重复)
numbers = {1, 2, 3, 4, 5}
empty_set = set() # 不能用 {},那是空字典
集合操作
numbers.add(6) # 添加
numbers.remove(3) # 移除(不存在会报错)
numbers.discard(10) # 移除(不存在不会报错)
numbers.pop() # 随机移除并返回一个元素
集合运算
a = {1, 2, 3}
b = {3, 4, 5}
a | b # {1, 2, 3, 4, 5} 并集
a & b # {3} 交集
a - b # {1, 2} 差集
a ^ b # {1, 2, 4, 5} 对称差集
集合推导式
squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
```
三、流程控制
1. 条件语句
```python
if-elif-else
age = 25
if age < 18:
print("未成年")
elif age < 60:
print("成年")
else:
print("老年")
三元表达式
status = "成年" if age >= 18 else "未成年"
match-case (Python 3.10+)
status_code = 404
match status_code:
case 200:
print("成功")
case 404:
print("未找到")
case 500:
print("服务器错误")
case _:
print("未知状态")
```
2. 循环语句
```python
for 循环
for i in range(5): # 0 到 4
print(i)
for char in "hello":
print(char)
for key, value in person.items():
print(key, value)
while 循环
count = 0
while count < 5:
print(count)
count += 1
循环控制
for i in range(10):
if i == 3:
continue # 跳过本次循环
if i == 7:
break # 退出循环
print(i)
else 子句(循环正常结束时执行)
for i in range(5):
print(i)
else:
print("循环完成") # 如果没有 break 会执行
enumerate(带索引的循环)
for index, value in enumerate(['a', 'b', 'c']):
print(index, value) # 0 a, 1 b, 2 c
zip(并行迭代)
names = ['张三', '李四', '王五']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
```
四、函数
1. 函数定义
```python
基础函数
def greet(name):
"""返回问候语(文档字符串)"""
return f"Hello, {name}!"
参数默认值
def power(x, n=2):
return x ** n
关键字参数
def person_info(name, age, city):
return f"{name}, {age}岁, 来自{city}"
person_info(name="张三", age=25, city="北京")
person_info(age=25, city="北京", name="张三") # 顺序不重要
可变位置参数 (*args)
def sum_all(*numbers):
return sum(numbers)
sum_all(1, 2, 3, 4, 5) # 15
可变关键字参数 (**kwargs)
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="张三", age=25, job="工程师")
混合参数(顺序:位置参数, *args, 默认参数, **kwargs)
def func(a, b, *args, option=True, **kwargs):
pass
```
2. 高阶函数
```python
lambda 表达式(匿名函数)
add = lambda x, y: x + y
add(3, 5) # 8
作为参数的函数
def apply_func(func, x, y):
return func(x, y)
apply_func(lambda a, b: a * b, 3, 4) # 12
map, filter, reduce
numbers = [1, 2, 3, 4, 5]
map:对每个元素应用函数
squares = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
filter:过滤元素
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
reduce:累积计算(需要导入)
from functools import reduce
total = reduce(lambda x, y: x + y, numbers) # 15
```
3. 装饰器
```python
基础装饰器
def my_decorator(func):
def wrapper():
print("函数执行前")
result = func()
print("函数执行后")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
带参数的装饰器
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}")
类装饰器
class Timer:
def init(self, func):
self.func = func
def call(self, *args, **kwargs):
import time
start = time.time()
result = self.func(*args, **kwargs)
end = time.time()
print(f"执行时间: {end - start:.2f}秒")
return result
@Timer
def slow_function():
import time
time.sleep(1)
```
五、面向对象编程
1. 类和对象
```python
基础类
class Person:
类属性(所有实例共享)
species = "人类"
初始化方法
def init(self, name, age):
实例属性
self.name = name
self.age = age
实例方法
def greet(self):
return f"你好,我叫{self.name}"
静态方法(不需要访问实例或类)
@staticmethod
def is_adult(age):
return age >= 18
类方法(操作类属性)
@classmethod
def create_baby(cls, name):
return cls(name, age=0)
魔术方法
def str(self):
return f"Person(name={self.name}, age={self.age})"
def repr(self):
return f"Person('{self.name}', {self.age})"
创建实例
person = Person("张三", 25)
print(person.greet()) # 你好,我叫张三
print(person) # Person(name=张三, age=25)
访问属性
person.name = "李四" # 修改属性
del person.age # 删除属性
hasattr(person, 'name') # True 检查属性
getattr(person, 'name', '无名') # 获取属性(带默认值)
```
2. 继承
```python
class Animal:
def init(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现此方法")
class Dog(Animal):
def init(self, name, breed):
super().init(name) # 调用父类构造
self.breed = breed
def speak(self):
return "汪汪!"
扩展父类方法
def describe(self):
return f"{super().speak()} 我是{self.name}, 一只{self.breed}"
多重继承
class A:
def method(self):
print("A")
class B:
def method(self):
print("B")
class C(A, B):
pass
c = C()
c.method() # "A"(MRO顺序)
print(C.mro) # 查看方法解析顺序
```
3. 属性封装
```python
class BankAccount:
def init(self, owner, balance):
self.owner = owner
self._balance = balance # 保护属性(约定)
self.__secret = "123456" # 私有属性(名称修饰)
属性装饰器(getter/setter)
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, amount):
if amount < 0:
raise ValueError("余额不能为负")
self._balance = amount
@balance.deleter
def balance(self):
print("删除余额")
del self._balance
account = BankAccount("张三", 1000)
print(account.balance) # 1000(调用getter)
account.balance = 1500 # 调用setter
account._balance # 可以访问但不推荐
account.__secret # 错误:AttributeError
account._BankAccount__secret # 可以访问(但不应该)
```
4. 抽象类
```python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def init(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
shape = Shape() # 错误:不能实例化抽象类
rect = Rectangle(5, 3)
```
六、异常处理
```python
基础异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零")
except (ValueError, TypeError) as e:
print(f"值或类型错误: {e}")
except Exception as e:
print(f"未知错误: {e}")
else:
print("没有异常时执行")
finally:
print("总是执行")
抛出异常
def validate_age(age):
if age < 0:
raise ValueError("年龄不能为负")
if age > 150:
raise ValueError("年龄不能超过150")
return True
自定义异常
class MyError(Exception):
def init(self, message):
self.message = message
def str(self):
return f"自定义错误: {self.message}"
断言
assert age >= 0, "年龄不能为负"
上下文管理器(with语句)
with open("file.txt", "r") as f:
content = f.read()
文件会自动关闭
自定义上下文管理器
class ManagedFile:
def init(self, filename, mode):
self.filename = filename
self.mode = mode
def enter(self):
self.file = open(self.filename, self.mode)
return self.file
def exit(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
if exc_type:
print(f"发生错误: {exc_val}")
return True # 抑制异常
```
七、文件操作
```python
打开文件
file = open("test.txt", "r") # 读取模式
file = open("test.txt", "w") # 写入模式(覆盖)
file = open("test.txt", "a") # 追加模式
file = open("test.txt", "r+") # 读写模式
读取文件
with open("file.txt", "r") as f:
content = f.read() # 读取全部内容
line = f.readline() # 读取一行
lines = f.readlines() # 读取所有行(列表)
逐行读取(推荐)
for line in f:
print(line.strip())
写入文件
with open("file.txt", "w") as f:
f.write("Hello\n") # 写入字符串
f.writelines(["Line 1\n", "Line 2\n"]) # 写入多行
二进制文件
with open("image.jpg", "rb") as f:
data = f.read()
JSON文件
import json
写入JSON
data = {"name": "张三", "age": 25}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
读取JSON
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
```
八、模块和包
```python
导入模块
import math # 导入整个模块
from math import sqrt, pi # 导入特定函数
import math as m # 别名
from math import * # 导入所有(不推荐)
创建包结构
"""
mypackage/
init.py
subpackage/
init.py
"""
init.py 内容
from .module1 import func1
from .module2 import func2
使用包
import mypackage.module1
from mypackage import module1
from mypackage.subpackage import module3
相对导入(在包内部)
from . import sibling_module
from .sibling_module import some_func
from ..parent_module import something
```
九、标准库重要模块
1. os 和 sys
```python
import os
import sys
os 模块
os.getcwd() # 当前工作目录
os.chdir("/path") # 改变目录
os.listdir(".") # 列出目录内容
os.mkdir("new_dir") # 创建目录
os.path.exists("file.txt") # 检查路径是否存在
os.path.join("dir", "file.txt") # 路径拼接
sys 模块
sys.argv # 命令行参数
sys.exit(0) # 退出程序
sys.path # Python路径
sys.platform # 操作系统
sys.version # Python版本
```
2. datetime
```python
from datetime import datetime, date, time, timedelta
当前时间
now = datetime.now()
today = date.today()
创建时间
dt = datetime(2024, 1, 20, 14, 30, 0)
格式化
dt.strftime("%Y-%m-%d %H:%M:%S") # "2024-01-20 14:30:00"
datetime.strptime("2024-01-20", "%Y-%m-%d")
时间运算
tomorrow = today + timedelta(days=1)
delta = dt2 - dt1 # 时间差
```
3. collections
```python
from collections import defaultdict, Counter, deque, namedtuple
defaultdict(带默认值的字典)
d = defaultdict(list)
d["key"].append(1) # 不需要先检查key是否存在
Counter(计数器)
counter = Counter("abracadabra")
counter.most_common(3) # [('a', 5), ('b', 2), ('r', 2)]
deque(双端队列)
queue = deque([1, 2, 3])
queue.append(4) # 右端添加
queue.appendleft(0) # 左端添加
queue.pop() # 右端移除
queue.popleft() # 左端移除
```
4. itertools
```python
import itertools
无限迭代器
itertools.count(10) # 10, 11, 12, ...
itertools.cycle("AB") # A, B, A, B, ...
itertools.repeat(10, 3) # 10, 10, 10
有限迭代器
list(itertools.combinations("ABCD", 2)) # 组合
list(itertools.permutations("AB", 2)) # 排列
list(itertools.product("AB", repeat=2)) # 笛卡尔积
```
十、异步编程
```python
import asyncio
异步函数
async def fetch_data():
print("开始获取数据")
await asyncio.sleep(2) # 模拟IO操作
print("数据获取完成")
return {"data": "some data"}
async def main():
运行单个任务
result = await fetch_data()
并发运行多个任务
task1 = asyncio.create_task(fetch_data())
task2 = asyncio.create_task(fetch_data())
results = await asyncio.gather(task1, task2)
超时控制
try:
await asyncio.wait_for(fetch_data(), timeout=1.0)
except asyncio.TimeoutError:
print("操作超时")
运行异步程序
asyncio.run(main())
```
十一、类型提示
```python
基本类型提示
def greet(name: str) -> str:
return f"Hello, {name}"
变量类型提示
age: int = 25
names: list[str] = ["张三", "李四"]
person: dict[str, any] = {"name": "张三", "age": 25}
复杂类型(需要导入)
from typing import List, Dict, Tuple, Optional, Union, Any
def process_items(
items: List[str],
counts: Dict[str, int],
point: Tuple[float, float],
description: Optional[str] = None,
data: Union[str, int] = "default"
) -> None:
pass
类型别名
Vector = List[float]
Matrix = List[Vector]
类型保护
def is_str(value: Any) -> TypeGuard[str]:
return isinstance(value, str)
```
十二、实用技巧
1. 列表/字典操作
```python
列表排序
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() # 原地排序
sorted_numbers = sorted(numbers) # 返回新列表
numbers.sort(key=lambda x: x % 2) # 自定义排序
列表去重
unique = list(set([1, 2, 2, 3, 3, 3]))
字典排序
sorted_by_key = dict(sorted(person.items()))
sorted_by_value = dict(sorted(person.items(), key=lambda x: x[1]))
字典合并(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # {'a': 1, 'b': 3, 'c': 4}
```
2. 生成器
```python
生成器函数
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1
for number in count_up_to(5):
print(number)
生成器表达式
squares = (x**2 for x in range(10))
next(squares) # 0
```
3. 解包操作
```python
序列解包
a, b, *rest = [1, 2, 3, 4, 5] # a=1, b=2, rest=[3,4,5]
first, *middle, last = [1, 2, 3, 4, 5]
字典解包
def show_info(name, age):
print(f"{name}: {age}")
person = {"name": "张三", "age": 25}
show_info(**person) # 等同于 show_info(name="张三", age=25)
```
**快速记忆要点:**
-
**缩进是语法**:使用4个空格(不要用Tab)
-
**鸭子类型**:"如果它走起来像鸭子,叫起来像鸭子,那么它就是鸭子"
-
**一切皆对象**:函数、类、模块都是对象
-
**列表推导式**:简洁创建列表的利器
-
**with语句**:确保资源被正确清理
-
**装饰器**:不修改原函数的情况下增强功能
-
**生成器**:节省内存的迭代方式
-
**f-string**:最简洁的字符串格式化方式
-
**类型提示**:Python 3.5+ 支持,提高代码可读性
-
**异步编程**:asyncio 处理并发IO操作
**常用快捷键(IPython/Jupyter):**
-
`?` - 显示帮助
-
`??` - 显示源代码
-
`%run script.py` - 运行脚本
-
`%timeit expression` - 计时
-
`%debug` - 进入调试器