03- Python 核心语法速查与实战指南
Python 核心语法速查与实战指南
一、常用数据类型与数据结构
Python 中最常用的四种容器类型:列表(list)、元组(tuple)、字典(dict)、集合(set)。它们支持“增删改查”,但特性不同。
1. 列表(list)—— 可变、有序、允许重复
✅ 适用场景:需要频繁修改、保持顺序的数据序列。
# 创建
fruits = ['apple', 'banana', 'cherry']
# 增
fruits.append('orange') # 末尾添加 → ['apple', 'banana', 'cherry', 'orange']
fruits.insert(1, 'grape') # 在索引1插入 → ['apple', 'grape', 'banana', ...]
fruits.extend(['mango', 'kiwi']) # 批量添加
# 删
fruits.remove('banana') # 删除第一个匹配项(不存在报错)
last = fruits.pop() # 弹出最后一个,返回值
first = fruits.pop(0) # 弹出索引0
del fruits[1] # 删除索引1(无返回)
fruits.clear() # 清空列表
# 改
fruits[0] = 'pear' # 直接赋值修改
# 查
print(fruits[1]) # 索引访问
print(fruits[-1]) # 倒数第一个
print(fruits[1:3]) # 切片 [start:end:step]
print('apple' in fruits) # 成员判断 → True/False
print(fruits.index('cherry')) # 返回首次出现索引(不存在报错)
# 其他
fruits.sort() # 就地排序(升序)
fruits.reverse() # 就地反转
copy_fruits = fruits.copy() # 浅拷贝
2. 元组(tuple)—— 不可变、有序、允许重复
✅ 适用场景:函数返回多个值、作为字典的键、保护数据不被修改。
# 创建
point = (3, 4)
colors = 'red', 'green', 'blue' # 括号可省略
# 查(只读!)
x, y = point # 解包
print(point[0]) # 3
print('green' in colors) # True
# ❌ 不能增、删、改!
# point[0] = 5 → TypeError
# 转换
lst = list(point) # tuple → list
t = tuple([1, 2, 3]) # list → tuple
3. 字典(dict)—— 可变、无序(Python 3.7+ 保持插入顺序)、键唯一
✅ 适用场景:存储属性、映射关系、快速查找。
# 创建
student = {'name': 'Alice', 'age': 20}
# 增 / 改(键存在则改,不存在则增)
student['city'] = 'Beijing'
student.update({'grade': 'A', 'age': 21}) # 批量更新
# 删
del student['grade']
age = student.pop('age') # 返回并删除(可设默认值)
student.popitem() # 弹出最后一对(3.7+ 是最后插入的)
# 查
print(student['name']) # KeyError 风险
print(student.get('phone', 'N/A')) # 安全访问
print('city' in student) # 判断键是否存在
# 遍历
for key in student: # 默认遍历键
print(key, student[key])
for k, v in student.items(): # 同时获取键值
print(k, v)
# 其他
keys = list(student.keys()) # 获取所有键
values = list(student.values()) # 获取所有值
4. 集合(set)—— 可变、无序、元素唯一
✅ 适用场景:去重、成员测试、数学集合运算。
# 创建
nums = {1, 2, 3, 3} # 自动去重 → {1, 2, 3}
letters = set('hello') # {'h', 'e', 'l', 'o'}
# 增
nums.add(4)
nums.update([5, 6, 7]) # 添加多个
# 删
nums.remove(1) # 不存在报错
nums.discard(10) # 不存在不报错
random_one = nums.pop() # 随机弹出一个(无序)
# 查
print(2 in nums) # True
# 集合运算
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 → {1,2,3,4,5}
print(a & b) # 交集 → {3}
print(a - b) # 差集 → {1,2}
print(a ^ b) # 对称差集 → {1,2,4,5}
# 不可变集合
frozen = frozenset([1, 2, 3]) # 可作为字典的键
二、类、方法与函数:面向对象核心语法精要
💡 核心思想:
- 类(Class) 是对象的模板
- 方法(Method) 是绑定到对象或类的函数
- 函数(Function) 是独立的可调用对象
- Python 不支持传统函数重载,但支持方法重写
1. 定义类与构造函数 __init__
class Student:
# 类属性:所有实例共享
school = "清华大学"
# 构造函数:创建对象时自动调用
def __init__(self, name, scores=None):
self.name = name # 实例属性
# ⚠️ 经典陷阱:不要用可变对象作默认参数!
self.scores = scores if scores is not None else []
✅ 关键点(高频考点):
__init__不是“构造函数”的全部,而是初始化方法;真正的构造由__new__完成(极少需重写)- 必须用
self作为第一个参数,代表当前实例 - 避免
def __init__(self, items=[])→ 多个实例会共享同一个列表!应使用None+ 条件赋值
创建对象
alice = Student("Alice", [90, 85])
bob = Student("Bob")
2. 三类方法:实例方法 / 类方法 / 静态方法(必考!)
实例方法 | 无 |
| 实例属性 + 类属性 | 对象行为(如
,
) |
类方法 |
|
| 类属性(不能访问实例属性) | 替代构造器(如
) |
静态方法 |
| 无 | 什么都不能直接访问 | 工具函数(与类逻辑相关但无需状态) |
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# 实例方法
def display(self):
return f"{self.year}-{self.month:02d}-{self.day:02d}"
# 类方法:替代构造器(经典用法!)
@classmethod
def from_string(cls, date_str):
"""从 '2025-12-24' 字符串创建 Date 对象"""
year, month, day = map(int, date_str.split('-'))
return cls(year, month, day) # 注意:用 cls 而不是 Date
# 静态方法:工具函数
@staticmethod
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
# 使用
d1 = Date(2025, 12, 24)
d2 = Date.from_string("2025-12-24") # ← 高频考察点!
print(d1.display()) # 2025-12-24
print(Date.is_leap_year(2024)) # True
🔥 面试高频问题:
Q:
@classmethod和@staticmethod有什么区别?A:
@classmethod接收类(cls),可用于创建新实例或操作类状态;@staticmethod就是一个普通函数,只是放在类里便于组织代码。
3. 继承与方法重写(Overriding)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal): # 继承 Animal
def speak(self): # 重写(Override)父类方法
return f"{self.name} says Woof!"
# 多态:同一接口,不同实现
animals = [Animal("Generic"), Dog("Buddy")]
for a in animals:
print(a.speak())
# Generic makes a sound.
# Buddy says Woof!
✅ 关键点:
- 子类自动继承父类的
__init__和方法 - 若子类定义了自己的
__init__,需显式调用父类初始化(用super()):
class Bird(Animal):
def __init__(self, name, can_fly=True):
super().__init__(name) # 调用父类 __init__
self.can_fly = can_fly
4. 关于“函数重载(Overloading)”的真相
❗ Python 不支持基于参数类型或数量的函数重载!
def add(a, b):
return a + b
def add(a, b, c): # 覆盖了上面的 add!
return a + b + c
add(1, 2) # ❌ 报错!只有两个参数的版本已不存在
✅ 正确做法(面试常问):
- 用默认参数处理可选输入
- 用
*args,**kwargs接收任意参数 - 用
functools.singledispatch实现基于类型的分发(高级)
# 推荐:默认参数 + 类型判断
def process(data, encoding='utf-8'):
if isinstance(data, str):
return data.upper()
elif isinstance(data, bytes):
return data.decode(encoding).upper()
else:
return str(data).upper()
🔑 重写(Overriding) vs 重载(Overloading):
- 重写:子类重新定义父类同名同参方法 → ✅ Python 支持
- 重载:同一作用域内多个同名但参数不同的函数 → ❌ Python 不支持
5. 普通函数:独立于类的可调用对象
虽然方法属于类,但 Python 中大量使用独立函数。它们是更基础的构建块。
函数定义与参数机制
def calculate_grade(score, curve=0, *bonus, **metadata):
"""
score: 必填位置参数
curve: 默认参数
*bonus: 可变位置参数(元组)
**metadata: 可变关键字参数(字典)
"""
total = score + curve + sum(bonus)
grade = 'A' if total >= 90 else 'B'
return {
'grade': grade,
'total': total,
'info': metadata
}
# 调用示例
result = calculate_grade(
85, # score
5, # curve
2, 3, # *bonus → (2, 3)
student="Alice", course="Math" # **metadata
)
Lambda 表达式(简短函数)
square = lambda x: x ** 2 get_name = lambda obj: obj.name if hasattr(obj, 'name') else 'Unknown'
⚠️ Lambda 仅适用于单表达式场景,复杂逻辑请用
def。
🧩 高频综合例题:安全初始化 + 多种构造方式
class User:
active_users = 0 # 类属性:统计在线用户
def __init__(self, username, email):
if not email or '@' not in email:
raise ValueError("Invalid email")
self.username = username
self.email = email
User.active_users += 1
@classmethod
def from_dict(cls, data):
"""从字典创建用户(常见于 JSON 解析)"""
return cls(data['username'], data['email'])
@staticmethod
def validate_email(email):
return isinstance(email, str) and '@' in email
def __del__(self):
User.active_users -= 1 # 简化版析构(实际慎用)
# 使用
user1 = User("alice", "alice@example.com")
user2 = User.from_dict({"username": "bob", "email": "**********"})
print(User.active_users) # 2
✅ 核心考点速记表
构造函数默认参数 | 用 | 直接用 |
调用父类初始化 |
| 忘记调用导致属性缺失 |
类方法 vs 静态方法 |
| 混淆两者用途 |
方法重写 | 子类定义同名同参方法 | 试图通过参数不同“重载” |
函数重载 | 用默认参数或 | 写多个同名函数导致覆盖 |
三、常用操作与内置函数(超全清单)
1. 类型与转换
a = 42
print(type(a)) # <class 'int'>
print(isinstance(a, int)) # True
# 类型转换
int("123") # → 123
float("3.14") # → 3.14
str(100) # → "100"
bool(0) # → False
list("abc") # → ['a','b','c']
tuple([1,2]) # → (1,2)
set([1,1,2]) # → {1,2}
dict([('a',1), ('b',2)]) # → {'a':1, 'b':2}
2. 字符串操作(高频!)
s = " Hello, World! "
# 去空格
s.strip() # 首尾
s.lstrip() # 左
s.rstrip() # 右
# 大小写
s.lower(), s.upper(), s.capitalize(), s.title()
# 分割与连接
s.split(',') # 按逗号分割 → list
s.split() # 按空白符分割(自动去空格)
'-'.join(['a','b']) # "a-b"
# 替换
s.replace('World', 'Python')
# 查找
s.find('World') # 返回索引(-1 表示未找到)
s.index('World') # 找不到报错
'World' in s # 推荐方式(返回 bool)
# 字母 ↔ ASCII
ord('A') # 65
chr(65) # 'A'
# 格式化(f-string 最推荐)
name, age = "Alice", 25
f"Hello, {name}. You are {age} years old."
3. 数值与格式化
# 进制转换
bin(10) # '0b1010'
oct(10) # '0o12'
hex(10) # '0xa'
# 保留小数
num = 3.14159
round(num, 2) # 3.14(四舍五入)
f"{num:.2f}" # "3.14"
"{:.3f}".format(num) # "3.142"
# 数学函数(需 import math)
import math
math.sqrt(16) # 4.0
math.ceil(3.2) # 4
math.floor(3.8) # 3
4. 序列操作
nums = [1, 2, 3, 4]
# map:对每个元素应用函数
list(map(str, nums)) # ['1','2','3','4']
list(map(lambda x: x*2, nums)) # [2,4,6,8]
# filter:过滤
list(filter(lambda x: x > 2, nums)) # [3,4]
# sorted:返回新列表(不修改原列表)
sorted(nums, reverse=True) # [4,3,2,1]
# reversed:返回迭代器
list(reversed(nums)) # [4,3,2,1]
# enumerate:带索引遍历
for i, val in enumerate(['a','b']):
print(i, val) # 0 a \n 1 b
# zip:并行遍历
list(zip([1,2], ['a','b'])) # [(1,'a'), (2,'b')]
5. 流程控制
# break:跳出整个循环
for i in range(5):
if i == 3:
break
print(i) # 0,1,2
# continue:跳过本次循环
for i in range(5):
if i == 2:
continue
print(i) # 0,1,3,4
# try-except:异常处理
try:
x = int(input("输入数字: "))
result = 10 / x
except ValueError:
print("输入的不是数字!")
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print("未知错误:", e)
else:
print("结果:", result) # 无异常时执行
finally:
print("结束") # 总是执行
6. 正则表达式(re 模块)
import re
text = "Email: user@example.com, Phone: xxxxxxxxx"
# match:从字符串开头匹配
re.match(r'\d+', "123abc") # 匹配成功
# search:全文搜索第一个匹配
email_match = re.search(r'\w+@\w+\.\w+', text)
if email_match:
print(email_match.group()) # user@example.com
# findall:找所有匹配
phones = re.findall(r'1[3-9]\d{9}', text) # ['xxxxxxxxx']
# sub:替换
clean = re.sub(r'\s+', ' ', "a b\tc") # "a b c"
# 编译提高效率(多次使用时)
pattern = re.compile(r'\d{4}')
pattern.findall("Year: 2024 and 2025") # ['2024', '2025']
💡 简单任务优先用
str方法(如replace,split),复杂模式再用正则。
四、综合实战例题
🧩 例题 1:安全解析用户输入的整数列表
def parse_int_list(s):
"""将 "1, 2, abc, 3" 转为 [1,2,3]"""
result = []
for part in s.split(','):
try:
num = int(part.strip())
result.append(num)
except ValueError:
continue
return result
print(parse_int_list("1, 2, abc, 3")) # [1, 2, 3]
🧩 例题 2:生成格式化价格表
products = [("苹果", 3.5), ("香蕉", 2.888)]
for name, price in products:
print(f"{name:>6}:¥{price:6.2f}")
# 输出:
# 苹果:¥ 3.50
# 香蕉:¥ 2.89
🧩 例题 3:提取文本中的邮箱和手机号
import re
def extract_contacts(text):
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
phones = re.findall(r'1[3-9]\d{9}', text)
return {"emails": emails, "phones": phones}
msg = "联系:user@test.com 或 xxxxxxx"#测试
print(extract_contacts(msg))
# {'emails': [**********'], 'phones': ['xxxxxxx']}
五、速查表
列表 |
,
,
,
,
,
| 可变序列 |
字典 |
,
,
,
,
,
| 键值映射 |
字符串 |
,
,
,
,
,
| 文本处理 |
数值 |
,
,
| 格式化 |
高阶函数 |
,
,
,
,
| 函数式编程 |
异常 |
,
,
,
| 错误处理 |
正则 |
,
,
| 模式匹配 |
大数据开发专栏 新手小白友好
