flowchart TD
A["Python 源代码 (.py)"] --> B["Python 解释器"]
B --> C["字节码 (.pyc)"]
C --> D["Python 虚拟机 PVM"]
D --> E["操作系统"]
E --> F["硬件"]
style A fill:#e1f5ff
style C fill:#fff3e0
style F fill:#e8f5e9
flowchart TD
A["调用函数"] --> B["传递实参"]
B --> C["绑定形参"]
C --> D["创建局部作用域"]
D --> E["执行函数体"]
E --> F{"有 return?"}
F -->|"是"--> G["返回值"]
F -->|"否"--> H["返回 None"]
G --> I["销毁局部作用域"]
H --> I
I --> J["回到调用点"]
style G fill:#c8e6c9
style H fill:#ffecb3
user = User("alice", "secret123") print(user.username) # alice print(user.password) # ****** print(user.check_password("secret123")) # True
# print(user.__password) # AttributeError: 访问不到!
类层次结构
flowchart TD
A["object 基类"] --> B["Animal 动物类"]
B --> C["Cat 猫类"]
B --> D["Dog 狗类"]
B --> E["Bird 鸟类"]
C --> C1["speak()"]
D --> D1["speak()"]
E --> E1["speak()"]
style A fill:#e8f5e9
style B fill:#c8e6c9
style C fill:#b2dfdb
style D fill:#b2dfdb
style E fill:#b2dfdb
模块与包
模块基础
Python 的模块就是一个 .py 文件。以下是标准库中的常用模块:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 导入整个模块 import math print(math.pi) # 3.141592653589793 print(math.sqrt(16)) # 4.0
# 导入特定成员 from random import randint, choice print(randint(1, 10)) # 1~10 随机整数 print(choice(["a", "b", "c"])) # 随机选一个
# 导入并起别名 import datetime as dt now = dt.datetime.now() print(now) # 2026-05-27 11:45:00.xxx
defvalidate_age(age): if age < 0: raise ValidationError("age", "年龄不能为负数") if age > 150: raise ValidationError("age", "年龄不合理") returnTrue
try: validate_age(-5) except ValidationError as e: print(e) # age: 年龄不能为负数
异常处理流程
flowchart TD
A["try 块"] --> B{"代码执行"}
B -->|"正常"--> C["else 块"]
B -->|"异常"--> D["except 块匹配"]
C --> E["finally 块"]
D --> E
E --> F["继续执行"]
D --> D1["不匹配则上抛"]
style C fill:#e8f5e9
style D fill:#ffcdd2
style E fill:#fff9c4
withopen("user.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2)
# 读取 JSON withopen("user.json", "r", encoding="utf-8") as f: loaded = json.load(f) print(loaded["name"]) # Alice
文件操作安全要点
flowchart TD
A["打开文件"] --> B{"使用 with?"}
B -->|"是"--> C["自动释放资源"]
B -->|"否"--> D["需手动 close()"]
D --> E["忘记 close 导致资源泄露"]
C --> F["读写操作"]
F --> G{"操作成功?"}
G -->|"是"--> H["正常处理"]
G -->|"否"--> I["捕获异常"]
I --> J["记录日志"]
style C fill:#c8e6c9
style D fill:#ffcdd2
style E fill:#ffcdd2
⚠️ 最佳实践:始终使用 with open(...) as f: 语句,它可以确保文件在使用完毕后自动关闭,即使中途发生异常也不会遗漏。
总结 🎯
以上我们梳理了 Python 的核心基础知识:
模块
核心要点
运行流程
解释执行,.py → 字节码 → PVM
数据类型
基本类型 + 四大容器(list/tuple/set/dict)
控制流程
if/elif/else + for/while + break/continue/pass
函数
def 定义、默认参数、*args、**kwargs、lambda、装饰器
面向对象
类、继承、多态、访问控制(私有属性)
模块
import/from、常用标准库、pip 安装三方库
异常处理
try/except/else/finally、自定义异常
文件操作
with open、读写文本、JSON 处理
Python 的设计哲学是:简洁优于复杂、明了优于隐晦。掌握这些基础后,你已经具备了继续深入 Web 开发、数据分析、人工智能等方向的核心能力。🚀
🐍 “Simple is better than complex” —— The Zen of Python