首页 > 基础资料 博客日记

Python 入门:从“其他语言”到 Pythonic 思维的完整迁移手册

2026-04-02 18:00:04基础资料围观1

这篇文章介绍了Python 入门:从“其他语言”到 Pythonic 思维的完整迁移手册,分享给大家做个参考,收藏极客资料网收获更多编程知识

想学学python搞ai应用开发,但是好多教程都是从“hello world" 开始,太痛苦了。因此,整理了这份文档。面向有编程基础的开发者,快速掌握 Python 开发全貌


一、环境管理

Python 版本管理

macOS / Linux(pyenv)

# 安装 pyenv
curl https://pyenv.run | bash

# 常用命令
pyenv install 3.12.0        # 安装指定版本
pyenv global 3.12.0         # 设置全局版本
pyenv local 3.11.0          # 设置当前目录版本(生成 .python-version)
pyenv versions              # 列出所有已安装版本
pyenv which python          # 查看当前 python 路径

Windows(PowerShell)

# 方式一:winget 直接安装(最简单)
# 设置国内源加速:winget source add winget https://mirrors.cernet.edu.cn/winget-source --trust-level trusted
winget search Python.Python        # 搜索可用版本
winget install Python.Python.3.12  # 安装
winget upgrade Python.Python.3.12  # 升级

# 验证(Windows 用 python,不是 python3)
python --version
pip --version

⚠️ 使用官网 .exe​ 安装包时,务必勾选 ​Add Python to PATH​,否则终端找不到 python 命令。

# 方式二:pyenv-win(推荐,支持多版本切换)
Invoke-WebRequest -UseBasicParsing `
  -Uri "https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1" `
  -OutFile "$HOME\install-pyenv-win.ps1"
& "$HOME\install-pyenv-win.ps1"

# 重启 PowerShell 后,命令与 Unix pyenv 完全相同
# 配置环境变量,使用加速源。环境变量名:PYTHON_BUILD_MIRROR_URL,值:https://registry.npmmirror.com/-/binary/python
pyenv install 3.12.0
pyenv global 3.12.0
pyenv local 3.11.0
pyenv versions
pyenv rehash              # 安装新版本后刷新 shims

# 如果 python 命令找不到,检查 PATH
where.exe python
$env:PATH -split ";"

虚拟环境

macOS / Linux

python -m venv .venv              # 创建
source .venv/bin/activate         # 激活
deactivate                        # 退出

Windows(PowerShell)

# 创建(与 Unix 相同)
python -m venv .venv

# 激活 —— PowerShell 专用,注意与 bash 不同!
.\.venv\Scripts\Activate.ps1

# 激活后提示符出现 (.venv) 前缀
# (.venv) PS C:\myproject>

# 退出
deactivate

# 删除虚拟环境
Remove-Item -Recurse -Force .venv

⚠️ 首次激活若报"无法加载文件"执行策略错误,运行一次即可解决:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
:: CMD(命令提示符)激活方式
.venv\Scripts\activate.bat
# Git Bash 激活方式
source .venv/Scripts/activate

conda(科学计算场景,跨平台)

conda create -n myenv python=3.12
conda activate myenv
conda deactivate

现代工具链(推荐 uv)

# uv:极速包管理器,兼容 pip 语法,Rust 编写
pip install uv

uv venv                           # 创建虚拟环境
uv pip install requests           # 安装包
uv pip sync requirements.txt      # 同步依赖

二、包管理

pip 基础命令

pip install requests              # 安装
pip install requests==2.31.0      # 安装指定版本
pip install "requests>=2.28,<3"   # 版本范围
pip uninstall requests            # 卸载
pip list                          # 列出已安装包
pip show requests                 # 查看包信息
pip freeze > requirements.txt     # 导出依赖
pip install -r requirements.txt   # 从文件安装
pip install -e .                  # 以开发模式安装当前包
pip install --upgrade requests    # 升级

requirements.txt

requests==2.31.0
numpy>=1.24.0
pandas
fastapi[all]>=0.100.0

pyproject.toml(现代项目标准)

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "my-project"
version = "0.1.0"
description = "My awesome project"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
    "requests>=2.28",
    "fastapi>=0.100",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "black",
    "mypy",
]

[project.scripts]
my-cli = "my_project.cli:main"    # 命令行入口

三、项目结构

标准项目结构

my_project/
├── .venv/                    # 虚拟环境(不提交 git)
├── .github/
│   └── workflows/            # CI/CD 配置
├── src/
│   └── my_project/           # 源代码(src layout,推荐)
│       ├── __init__.py
│       ├── main.py           # 主程序
│       ├── config.py         # 配置
│       ├── models/
│       │   ├── __init__.py
│       │   └── user.py
│       ├── services/
│       │   ├── __init__.py
│       │   └── user_service.py
│       └── utils/
│           ├── __init__.py
│           └── helpers.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py           # pytest 配置/fixtures
│   ├── test_main.py
│   └── services/
│       └── test_user_service.py
├── docs/
├── scripts/                  # 工具脚本
├── .env                      # 环境变量(不提交 git)
├── .env.example              # 环境变量示例(提交 git)
├── .gitignore
├── pyproject.toml            # 项目配置(现代标准)
├── requirements.txt          # 依赖(可选)
└── README.md

简单脚本结构

simple_app/
├── app.py
├── requirements.txt
└── .env

四、程序入口

# main.py

def main():
    print("Hello, Python!")

# 关键:判断是否作为主程序运行(而非被导入)
if __name__ == "__main__":
    main()
# 运行方式
python main.py
python -m my_project.main    # 以模块方式运行

命令行参数

import argparse

def main():
    parser = argparse.ArgumentParser(description="My tool")
    parser.add_argument("name", help="Your name")
    parser.add_argument("-v", "--verbose", action="store_true")
    parser.add_argument("--count", type=int, default=1)
    args = parser.parse_args()

    for _ in range(args.count):
        print(f"Hello, {args.name}!")

if __name__ == "__main__":
    main()

五、基础语法

变量与赋值

# 变量赋值示例
x = 10 # 动态类型,可以随时改变类型
print(x) # 输出 10
x = "Hello, World!" # 现在 x 是一个字符串
print(x) # 输出 "Hello, World!"


x, y, z = 20, 30, 40 # 多变量赋值
print(x, y, z) # 输出 20 30 40

a = b = c = 50 # 链式赋值
print(a, b, c) # 输出 50 50 50

x, *rest = [1, 2, 3, 4, 5] # 解包赋值,rest 将包含剩余的值
print(x) # 输出 1
print(rest) # 输出 [2, 3, 4, 5]

_, second, *_ = [10, 20, 30, 40] # 使用 _ 忽略不需要的值
print(second) # 输出 20

# 命名规范

my_variable = 100 # 变量名应该使用小写字母和下划线分隔(snake_case)
MY_CONSTANT = 3.14 # 常量名应该使用大写字母和下划线分隔(UPPER_SNAKE_CASE)
MyClass = "This is a class name" # 类名应该使用大写字母开头的驼峰命名法(PascalCase)
_private_variable = "This is a private variable" # 私有变量通常以单下划线开头
__dunder_variable__ = "This is a dunder variable" # 双下划线变量通常用于特殊用途,如 __init__ 或 __str__

注释

# 单行注释

"""
多行注释示例
这是一个多行注释的示例,可以用于函数说明文档或者代码块的解释。
"""

def example_function(param1, param2) -> str:
    """ 函数说明文档

    Args:
        param1 (int): 这是第一个参数的说明
        param2 (str): 这是第二个参数的说明
    Returns:
        str: 这是函数返回值的说明
    """
    pass # 这里是函数体的占位符,实际代码应该在这里编写

基本运算

# 算术
10 + 3    # 13
10 - 3    # 7
10 * 3    # 30
10 / 3    # 3.3333...(真除法,始终返回 float)
10 // 3   # 3(整除)
10 % 3    # 1(取余)
10 ** 3   # 1000(幂运算)

# 比较(返回 bool)
x == y    # 等于
x != y    # 不等于
x > y     # 大于
x >= y    # 大于等于

# 逻辑
True and False   # False
True or False    # True
not True         # False

# 成员 & 身份
x in [1, 2, 3]       # True/False
x not in [1, 2, 3]
x is None            # 身份比较(比较对象地址)
x is not None

六、数据类型

数字

i = 42              # int(任意精度)
f = 3.14            # float
c = 1 + 2j          # complex
b = True            # bool(int 的子类,True==1, False==0)

# 转换
int("42")           # 42
float("3.14")       # 3.14
str(42)             # "42"
bool(0)             # False(0, "", [], None 均为 falsy)

# 数字字面量
1_000_000           # 下划线分隔(可读性)
0xFF                # 十六进制
0b1010              # 二进制
0o17                # 八进制

字符串

s = "hello"
s = 'hello'
s = """多行
字符串"""

# f-string(推荐,Python 3.6+)
name = "Alice"
print(f"Hello, {name}!")
print(f"2 + 3 = {2 + 3}")
print(f"{3.14159:.2f}")  # 格式化浮点数, 保留两位小数
print(f"{{}}")  # 输出花括号
print(f"{1000000:,}")  # 数字千位分隔符, 1,000,000
print(f"{'Alice':>10}")  # 右对齐,      Alice
print(f"{'Bob':<10}")  # 左对齐, Bob       

# 常用方法
s.upper() / s.lower()
s.strip() / s.lstrip() / s.rstrip()    # 去空白
s.split(",") / ",".join(["a","b"])
s.replace("old", "new")
s.startswith("he") / s.endswith("lo")
s.find("ll")               # 返回索引,找不到返回 -1
s.count("l")
s.format(name="Alice")     # 旧式格式化

# 切片
s = "Hello"
s[0]       # 'H'
s[-1]      # 'o'
s[1:3]     # 'el'
s[::-1]    # 'olleH'(反转)


# s[0] = "h"  ❌ # 字符串是不可变的,会报错

列表 list

lst = [1, 2, 3, "four", True]   # 可混合类型
lst = list(range(5))             # [0,1,2,3,4]

# 增删改查
lst.append(5)                    # 末尾添加
lst.insert(0, 99)                # 指定位置插入
lst.extend([6, 7])               # 追加多个
lst.remove(99)                   # 删除第一个匹配值
popped = lst.pop()               # 删除并返回末尾
popped = lst.pop(0)              # 删除并返回指定索引
del lst[0]                       # 删除指定索引
lst[0] = 100                     # 修改

# 查询
lst[0]          # 索引访问
lst[-1]         # 最后一个
lst[1:3]        # 切片
len(lst)
lst.index(2)    # 返回索引
lst.count(2)    # 计数
2 in lst        # True/False

# 排序
lst.sort()                        # 原地排序
lst.sort(reverse=True)
lst.sort(key=lambda x: x[1])     # 自定义排序键
sorted(lst)                       # 返回新列表,不修改原列表

# 列表推导式(重要!)
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
flat = [item for sublist in [[1,2],[3,4]] for item in sublist]

元组 tuple

t = (1, 2, 3)          # 不可变
t = 1, 2, 3            # 括号可省略
t = (42,)              # 单元素元组(注意逗号)
t = tuple([1, 2, 3])

t[0]                   # 访问
a, b, c = t            # 解包
len(t)
t.count(1) # 统计元素出现的次数
t.index(2) # 返回元素第一次出现的索引

# 元组可作字典键(list 不行)
d = {(0, 0): "origin"}

字典 dict

d = {"name": "Alice", "age": 30}
d = dict(name="Alice", age=30)
d = {i: i**2 for i in range(5)}   # 字典推导式

# 增删改查
d["name"]                   # 访问(KeyError if missing)
d.get("name")               # 安全访问,默认返回 None
d.get("x", "default")       # 指定默认值
d["email"] = "a@b.com"      # 添加/修改
del d["age"]                # 删除
d.pop("age", None)          # 删除并返回(带默认值)

# 遍历
d.keys()
d.values()
d.items()                   # (key, value) 对
for k, v in d.items():
    print(k, v)

# 合并(Python 3.9+)
merged = d1 | d2
d1 |= d2                   # 原地合并

# 其他
"name" in d                 # 检查 key 是否存在
d.setdefault("x", 0)        # 不存在则设置默认值
d.update({"a": 1})          # 批量更新

集合 set

s = {1, 2, 3}
s = set([1, 2, 2, 3])      # {1, 2, 3}(自动去重)
s = set()                   # 空集合(注意:{} 是空字典)

s.add(4)
s.remove(1)                 # KeyError if missing
s.discard(99)               # 安全删除,不存在不报错

# 集合运算
a | b           # 并集
a & b           # 交集
a - b           # 差集(在 a 不在 b)
a ^ b           # 对称差(在 a 或 b,但不同时在)
a.issubset(b)   # a ⊆ b
a.issuperset(b)

# 集合推导式
s = {x**2 for x in range(10)}

None 与布尔

x = None           # 空值(类似 null)
x is None          # 推荐判断方式

# Falsy 值
bool(None)         # False
bool(0)            # False
bool("")           # False
bool([])           # False
bool({})           # False
bool(set())        # False

# Truthy:其他所有值

七、控制流

条件

if x > 0:
    print("正数")
elif x < 0:
    print("负数")
else:
    print("零")

# 三元表达式
result = "yes" if condition else "no"

# match-case(Python 3.10+,类似 switch)
match command:
    case "quit":
        quit()
    case "hello":
        print("Hello!")
    case {"action": action, "value": value}:   # 匹配字典
        print(action, value)
    case _:                                     # 默认分支
        print("Unknown")

循环

# for 循环
for i in range(5):          # 0,1,2,3,4
    print(i)

for i in range(2, 10, 2):   # 2,4,6,8(步长2)
    pass

for item in [1, 2, 3]:
    pass

for i, item in enumerate(["a","b","c"]):    # 带索引
    print(i, item)

for k, v in d.items():      # 遍历字典

for a, b in zip([1,2,3], ["x","y","z"]):   # 并行遍历
    print(a, b)

# while 循环
while condition:
    pass

# 控制
break                        # 退出循环
continue                     # 跳到下一次
for ... else:                # 循环正常结束(未被break)时执行 else
    pass
else:
    print("loop done")

八、函数

基础

def greet(name, greeting="Hello"):    # 默认参数
    """函数文档字符串。"""
    return f"{greeting}, {name}!"

# 调用
greet("Alice")
greet("Alice", greeting="Hi")        # 关键字参数
greet(greeting="Hi", name="Alice")   # 关键字参数顺序无关

参数类型

符号 位置 规则
/ 参数列表之中 左边的参数必须用位置传参
* 参数列表之中 右边的参数必须用关键字传参(key=value
顺序 参数类型 描述 示例
1 必选参数 必须提供的基础参数 def func(a, b):
2 默认参数 带有默认值的参数 def func(a, b=10):
3 可变参数 收集多余的位置参数 (*args) def func(a, *args):
4 关键字可变参数 收集多余的键值对 (**kwargs) def func(a, **kwargs):
def func(a, b, /, c, *, d, e):
    # a, b:仅位置参数(/前)
    # c:普通参数
    # d, e:仅关键字参数(*后)
    pass

def variadic(*args, **kwargs):
    print(args)    # 元组
    print(kwargs)  # 字典

variadic(1, 2, 3, x=4, y=5)
# args = (1, 2, 3)
# kwargs = {'x': 4, 'y': 5}

# 解包传参
lst = [1, 2, 3]
func(*lst)          # 解包列表
func(**{"a": 1})    # 解包字典

Lambda 函数

add = lambda x, y: x + y
add(1, 2)            # 3

# 常用于 sort/map/filter
sorted(data, key=lambda x: x["age"])
list(map(lambda x: x*2, [1,2,3]))
list(filter(lambda x: x > 0, [-1, 0, 1, 2]))

函数特性

# 函数是一等公民(可作参数、返回值)
def apply(func, value):
    return func(value)

apply(str.upper, "hello")

# 闭包
def make_counter():
    count = 0
    def counter():
        nonlocal count     # 修改外部变量用 nonlocal
        count += 1
        return count
    return counter

c = make_counter()
c()  # 1
c()  # 2

九、面向对象

基础类

什么时候使用:当你的类包含复杂的业务逻辑、需要复杂的继承体系,或者你需要严格控制属性的访问权限

class Animal:
    # 类变量(所有实例共享)
    species_count = 0

    def __init__(self, name: str, age: int):
        # 实例变量,每个实例独有的
        self.name = name
        self.age = age
        self._weight = 0        # 约定受保护
        self.__secret = "..."   # 名称改写(mangling)
        Animal.species_count += 1

    def __repr__(self):
        """开发者表示,优先级高"""
        return f"Animal(name={self.name!r}, age={self.age})"

    def __str__(self):
        """用户友好表示"""
        return f"{self.name} ({self.age}岁)"

    def __len__(self):
        return self.age

    def __eq__(self, other):
        return isinstance(other, Animal) and self.name == other.name

    def speak(self): # 普通方法,必须由实例调用
        raise NotImplementedError

    @classmethod # 类方法,第一个参数是类本身
    def create(cls, name):
        """类方法,第一个参数是类本身"""
        return cls(name, 0)

    @staticmethod # 静态方法,是工具函数
    def validate_age(age):
        """静态方法,与类/实例无关"""
        return age >= 0

    @property # Getter,使用`a.weight`会调用这个函数
    def weight(self):
        """属性装饰器(getter)"""
        return self._weight

    @weight.setter # Setter,`a.weight = -5`会调用这个函数
    def weight(self, value):
        if value < 0:
            raise ValueError("体重不能为负")
        self._weight = value

继承

class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)   # 调用父类初始化
        self.breed = breed

    def speak(self):
        return "Woof!"

    def __repr__(self):
        return f"Dog(name={self.name!r}, breed={self.breed!r})"

# 多继承
class C(A, B):
    pass
# MRO(方法解析顺序):C → A → B → object
print(C.__mro__)

数据类(Python 3.7+)

什么时候使用:当你的类主要目的是存储数据(如数据库记录、配置信息、API 响应)

from dataclasses import dataclass, field

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0                       # 默认值
    tags: list = field(default_factory=list)  # 可变默认值用 field

    def distance(self):
        return (self.x**2 + self.y**2) ** 0.5

p = Point(1.0, 2.0)
# 自动生成 __init__, __repr__, __eq__

@dataclass(frozen=True)     # 不可变
class FrozenPoint:
    x: float
    y: float

抽象类

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        pass

    @abstractmethod
    def perimeter(self) -> float:
        pass

class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius

    def area(self):
        import math
        return math.pi * self.radius ** 2

    def perimeter(self):
        import math
        return 2 * math.pi * self.radius

十、模块与包

导入

import os                         # 导入模块
import os.path                    # 导入子模块
from os import path               # 导入模块中的名称
from os.path import join, exists  # 导入多个
from os import *                  # 导入全部(不推荐)
import numpy as np                # 别名(惯例)
from . import utils               # 相对导入(同包内)
from ..models import User         # 相对导入(上级包)

__init__.py

# my_package/__init__.py
# 控制 from my_package import * 时暴露的内容
__all__ = ["MyClass", "my_function"]

from .my_module import MyClass
from .utils import my_function

__version__ = "0.1.0"

十一、异常处理

# 捕获异常
try:
    result = 10 / 0
except ZeroDivisionError:
    print("除零错误")
except (TypeError, ValueError) as e:
    print(f"类型或值错误: {e}")
except Exception as e:
    print(f"未知错误: {e}")
    raise           # 重新抛出
else:
    print("无异常时执行")
finally:
    print("始终执行(清理资源)")

# 抛出异常
raise ValueError("无效的值")
raise ValueError("无效的值") from original_error   # 异常链

# 自定义异常
class AppError(Exception):
    """应用基础异常"""
    pass

class NotFoundError(AppError):
    def __init__(self, resource, id):
        self.resource = resource
        self.id = id
        super().__init__(f"{resource} with id={id} not found")

# 常见内置异常
# Exception, ValueError, TypeError, KeyError, IndexError
# AttributeError, NameError, ImportError, FileNotFoundError
# RuntimeError, StopIteration, NotImplementedError
# OverflowError, MemoryError, RecursionError

十二、文件操作

# 读文件(推荐 with 语句,自动关闭)
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()          # 全部读取为字符串
    lines = f.readlines()       # 读取所有行为列表
    for line in f:              # 逐行读取(节省内存)
        print(line.strip())

# 写文件
with open("file.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")
    f.writelines(["line1\n", "line2\n"])

# 追加
with open("file.txt", "a") as f:
    f.write("new line\n")

# 二进制
with open("image.png", "rb") as f:
    data = f.read()

# 文件模式
# "r"  只读(默认)
# "w"  写入(覆盖)
# "a"  追加
# "x"  创建(已存在则报错)
# "b"  二进制模式
# "+"  读写模式

# pathlib(现代文件路径,推荐)
from pathlib import Path

p = Path("./data")
p.mkdir(parents=True, exist_ok=True)

file = p / "output.txt"           # 路径拼接
file.write_text("Hello", encoding="utf-8")
content = file.read_text(encoding="utf-8")
file.exists()
file.is_file() / file.is_dir()
file.suffix                        # ".txt"
file.stem                          # "output"
file.name                          # "output.txt"
file.parent                        # Path("./data")
list(p.glob("*.txt"))              # 匹配文件
list(p.rglob("*.py"))             # 递归匹配

# JSON
import json
with open("data.json", "w") as f:
    json.dump({"key": "value"}, f, indent=2, ensure_ascii=False)

with open("data.json") as f:
    data = json.load(f)

json.dumps(obj)     # 对象 → 字符串
json.loads(s)       # 字符串 → 对象

十三、迭代器与生成器

迭代器协议

# 实现 __iter__ 和 __next__
class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        self.current += 1
        return self.current

生成器(更简洁)

# 生成器函数(含 yield)
def countdown(n):
    while n > 0:
        yield n        # 暂停并返回值
        n -= 1

for x in countdown(5):
    print(x)

# 生成器表达式(惰性求值,节省内存)
gen = (x**2 for x in range(1000000))   # 不立即计算
next(gen)                               # 按需获取

# yield from(委托子生成器)
def chain(*iterables):
    for it in iterables:
        yield from it

# 实用函数
import itertools
itertools.chain([1,2], [3,4])           # 串联
itertools.product([1,2], ["a","b"])     # 笛卡尔积
itertools.groupby(data, key=lambda x: x["type"])
itertools.islice(gen, 10)               # 切片生成器

import functools
functools.reduce(lambda a, b: a+b, [1,2,3,4])   # 折叠

十四、装饰器

import functools

# 基础装饰器
def my_decorator(func):
    @functools.wraps(func)          # 保留原函数元信息
    def wrapper(*args, **kwargs):
        print("before")
        result = func(*args, **kwargs)
        print("after")
        return result
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

# 带参数的装饰器
def repeat(n):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(n):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

# 常用内置装饰器
@staticmethod           # 静态方法
@classmethod            # 类方法
@property               # 属性
@functools.lru_cache(maxsize=128)   # 缓存(记忆化)
@functools.cache        # Python 3.9+,无大小限制的缓存

十五、上下文管理器

# 实现 __enter__ 和 __exit__
class Timer:
    import time

    def __enter__(self):
        self.start = self.time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.elapsed = self.time.time() - self.start
        return False    # False: 不抑制异常;True: 抑制异常

with Timer() as t:
    # do something
    pass
print(f"耗时: {t.elapsed:.3f}s")

# 使用 contextlib(更简洁)
from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("获取资源")
    try:
        yield "resource"      # yield 之前是 __enter__
    finally:
        print("释放资源")     # finally 是 __exit__

with managed_resource() as r:
    print(f"使用 {r}")

十六、并发编程

多线程(I/O 密集型)

import threading

def worker(n):
    print(f"线程 {n} 运行")

threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()

# 线程安全
lock = threading.Lock()
with lock:
    # 临界区
    pass

多进程(CPU 密集型)

from multiprocessing import Pool

def square(n):
    return n ** 2

with Pool(processes=4) as pool:
    results = pool.map(square, range(10))

异步 I/O(asyncio)

import asyncio

async def fetch_data(url):
    await asyncio.sleep(1)        # 模拟异步 I/O
    return f"data from {url}"

async def main():
    # 并发执行多个任务
    tasks = [fetch_data(url) for url in ["a.com", "b.com", "c.com"]]
    results = await asyncio.gather(*tasks)
    print(results)

asyncio.run(main())     # 运行事件循环

# async with / async for
async def read_file():
    async with aiofiles.open("file.txt") as f:   # 需要 aiofiles 库
        async for line in f:
            print(line)

concurrent.futures(高层接口)

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

# 线程池
with ThreadPoolExecutor(max_workers=4) as executor:
    futures = [executor.submit(func, arg) for arg in args]
    results = [f.result() for f in futures]

# map 方式(更简洁)
with ThreadPoolExecutor() as executor:
    results = list(executor.map(func, args))

十七、类型注解

# Python 3.10+ 推荐写法
from __future__ import annotations   # Python 3.7-3.9 启用新语法

# 基础类型
x: int = 1
y: float = 3.14
s: str = "hello"
b: bool = True
n: None = None

# 容器
lst: list[int] = [1, 2, 3]
tpl: tuple[int, str, float] = (1, "a", 3.14)
dct: dict[str, int] = {"a": 1}
st: set[int] = {1, 2, 3}

# 可选值
def func(x: int | None = None) -> str:   # Python 3.10+
    pass

from typing import Optional
def func(x: Optional[int] = None) -> str:  # 旧写法
    pass

# Union(多类型)
def func(x: int | str) -> None:
    pass

# 可调用
from typing import Callable
def apply(f: Callable[[int, int], int], a: int, b: int) -> int:
    return f(a, b)

# 泛型
from typing import TypeVar, Generic
T = TypeVar("T")

def first(lst: list[T]) -> T:
    return lst[0]

# 类型别名
Vector = list[float]
Matrix = list[list[float]]

# TypedDict
from typing import TypedDict

class UserDict(TypedDict):
    name: str
    age: int
    email: str

# Protocol(结构化子类型)
from typing import Protocol

class Drawable(Protocol):
    def draw(self) -> None: ...

# 静态检查工具
# mypy: pip install mypy && mypy my_module.py
# pyright: pip install pyright

十八、常用标准库

os / sys / pathlib

import os
os.getcwd()                     # 当前目录
os.listdir(".")                 # 列出目录
os.makedirs("a/b/c", exist_ok=True)
os.environ.get("HOME")          # 环境变量
os.path.join("a", "b", "c")    # 路径拼接

import sys
sys.argv                        # 命令行参数
sys.path                        # 模块搜索路径
sys.exit(0)                     # 退出
sys.version                     # Python 版本

datetime

from datetime import datetime, date, timedelta

now = datetime.now()
today = date.today()
dt = datetime(2024, 1, 15, 10, 30, 0)

# 格式化
dt.strftime("%Y-%m-%d %H:%M:%S")     # datetime → str
datetime.strptime("2024-01-15", "%Y-%m-%d")   # str → datetime

# 运算
tomorrow = today + timedelta(days=1)
delta = datetime.now() - dt
delta.days
delta.total_seconds()

collections

from collections import (
    defaultdict,    # 带默认值的字典
    Counter,        # 计数器
    OrderedDict,    # 有序字典(Python 3.7+ 普通 dict 也有序)
    deque,          # 双端队列
    namedtuple,     # 命名元组
    ChainMap,       # 多字典链
)

# defaultdict
dd = defaultdict(list)
dd["key"].append(1)              # 无需检查 key 是否存在

# Counter
c = Counter("abracadabra")
c.most_common(3)                 # [('a', 5), ('b', 2), ('r', 2)]
c["a"]                           # 5

# deque(O(1) 两端操作)
dq = deque([1, 2, 3], maxlen=5)
dq.appendleft(0)
dq.popleft()
dq.rotate(1)                     # 右旋

# namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
p.x, p.y

re(正则表达式)

import re

pattern = r"\d+"                    # r 前缀表示原始字符串

re.match(pattern, "123abc")         # 从头匹配
re.search(pattern, "abc123")        # 全文搜索,返回第一个
re.findall(pattern, "a1b2c3")       # 返回所有匹配 ["1","2","3"]
re.sub(pattern, "X", "a1b2")        # 替换 → "aXbX"
re.split(r"\s+", "a  b  c")         # 分割 → ["a","b","c"]

# 编译(多次使用时更高效)
pat = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})")
m = pat.search("date: 2024-01")
m.group("year")                     # "2024"
m.group("month")                    # "01"

# 常用模式
# \d  数字  \w  字母数字下划线  \s  空白
# .   任意字符  ^  开头  $  结尾
# *   0+  +  1+  ?  0或1  {n,m}  次数
# (?:...)  非捕获组  (?=...)  前瞻

logging

import logging

# 基础配置
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("app.log"),
    ]
)

logger = logging.getLogger(__name__)

logger.debug("调试信息")
logger.info("普通信息")
logger.warning("警告")
logger.error("错误")
logger.critical("严重错误")
logger.exception("带异常信息的错误")   # 自动附加 traceback

functools / itertools

import functools

functools.partial(pow, 2)           # 偏函数:固定部分参数
functools.reduce(lambda a,b: a+b, lst)
functools.lru_cache(maxsize=128)    # 缓存装饰器

import itertools
itertools.chain(*iterables)
itertools.combinations([1,2,3], 2)  # 组合
itertools.permutations([1,2,3], 2)  # 排列
itertools.product("AB", repeat=2)   # 笛卡尔积
itertools.cycle([1,2,3])            # 无限循环
itertools.islice(it, 10)            # 切片迭代器

dataclasses / enum

from enum import Enum, auto

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = auto()      # 自动赋值

Color.RED
Color.RED.value        # 1
Color.RED.name         # "RED"
Color["RED"]           # 按名称访问
list(Color)            # 所有成员

typing / abc(见类型注解和抽象类章节)


十九、测试

pytest(推荐)

pip install pytest pytest-cov
pytest                          # 运行所有测试
pytest tests/test_foo.py        # 运行指定文件
pytest -k "test_add"            # 按名称过滤
pytest -v                       # 详细输出
pytest --cov=src --cov-report=html   # 覆盖率报告
# tests/test_math.py
import pytest
from my_project.math import add, divide

def test_add_positive():
    assert add(1, 2) == 3

def test_add_negative():
    assert add(-1, -1) == -2

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
])
def test_add_parametrize(a, b, expected):
    assert add(a, b) == expected

# conftest.py:共享 fixtures
@pytest.fixture
def user():
    return {"name": "Alice", "age": 30}

def test_user(user):
    assert user["name"] == "Alice"

# Mock
from unittest.mock import patch, MagicMock

def test_with_mock():
    with patch("my_module.requests.get") as mock_get:
        mock_get.return_value.json.return_value = {"key": "value"}
        result = my_function()
        mock_get.assert_called_once()

二十、常用第三方库速览

类别 说明
HTTP 客户端 requests 同步 HTTP
HTTP 客户端 httpx 同步+异步 HTTP
Web 框架 fastapi 现代异步 API 框架
Web 框架 flask 轻量 Web 框架
Web 框架 django 全栈 Web 框架
数据处理 pandas 表格数据分析
数值计算 numpy 数组/矩阵运算
数据库 ORM sqlalchemy 通用 ORM
数据库 ORM tortoise-orm 异步 ORM
数据验证 pydantic 数据模型/验证
环境变量 python-dotenv 加载 .env 文件
CLI 工具 typer 基于类型注解的 CLI
CLI 工具 click 命令行接口框架
序列化 orjson 高性能 JSON
日期时间 arrow 友好的日期时间库
任务队列 celery 分布式任务队列
测试 Mock pytest-mock pytest Mock 插件
代码格式化 black 代码格式化
Linter ruff 极速 Linter+Formatter
类型检查 mypy 静态类型检查

附录:Python 与其他语言对比速查

概念 Python Java/C# JavaScript
空值 None null null/undefined
打印 print() System.out.println() console.log()
字符串插值 f"Hello {name}" $"Hello {name}"|​`Hello ${name}`
数组/列表 list ArrayList Array
字典/映射 dict HashMap Object/Map
接口 Protocol/ABC interface -
枚举 Enum enum -
异步 async/await async/await async/await
包管理 pip/uv Maven/Gradle npm/yarn
整除 // /(int) Math.floor(a/b)
幂运算 ** Math.pow() **
逻辑运算符 and/or/not &&/||/! &&/||/!

本手册基于 Python 3.10+ 编写。建议配合官方文档 docs.python.org 深入学习。


文章来源:https://www.cnblogs.com/denglei1024/p/19813444/python-complete-reference-manual-1vzwm8
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云