Jacky's blog
首页
  • 学习笔记

    • web
    • android
    • iOS
    • vue
  • 分类
  • 标签
  • 归档
收藏
  • tool
  • algo
  • python
  • java
  • server
  • growth
  • frida
  • blog
  • SP
  • more
GitHub (opens new window)

Jack Yang

编程; 随笔
首页
  • 学习笔记

    • web
    • android
    • iOS
    • vue
  • 分类
  • 标签
  • 归档
收藏
  • tool
  • algo
  • python
  • java
  • server
  • growth
  • frida
  • blog
  • SP
  • more
GitHub (opens new window)
  • python 学习指南
    • 学习目标
    • 1. Python 基础语法
      • 1.1 环境搭建
      • 1.2 基本概念
      • 1.3 数据类型
      • 数值类型
      • 字符串类型
      • 序列类型
      • 1.4 变量和赋值
      • 1.5 运算符
    • 2. 控制流程
      • 2.1 条件语句
      • 2.2 循环语句
      • 2.3 异常处理
    • 3. 函数和模块
      • 3.1 函数定义
      • 3.2 函数高级特性
      • 3.2.1 匿名函数(lambda)
      • 3.2.2 装饰器
      • 3.2.3 生成器(Generator)
      • 生成器函数
      • 生成器表达式
      • 生成器的优势
      • 生成器的高级用法
      • 生成器与迭代器的关系
      • 3.3 模块和包
      • 3.4 常用模块介绍
      • 基础模块
      • 文件和数据模块
      • 网络和通信模块
      • 并发和异步模块
      • 数据处理模块
      • 数据库模块
      • Web 开发模块
      • 测试模块
      • 系统管理模块
      • 图像和多媒体模块
      • 安全和加密模块
      • 其他实用模块
    • 4. 面向对象编程
      • 4.1 类和对象
      • 4.2 继承和多态
      • 4.3 特殊方法
      • 4.3.1 装饰器(Decorators)
      • @property 装饰器
      • @dataclass 装饰器(Python 3.7+)
      • @staticmethod 和 @classmethod 装饰器
      • @functools.lru_cache 装饰器
      • 自定义装饰器
      • 常用内置装饰器
      • 装饰器最佳实践
      • 4.4 基类和元类
      • 基类(Base Class)
      • 抽象基类(Abstract Base Class)
      • 元类(Metaclass)
      • 基本概念
      • 使用type创建类
      • 自定义元类
      • 元类的实际应用
      • 属性验证元类
      • 自动注册元类
      • 元类的高级用法
      • 4.5 元类和基类的最佳实践
    • 5. 数据处理基础
      • 5.1 文件操作
      • 5.2 字符串处理
      • 5.2.1 字符串切片 (String Slicing)
      • 5.2.2 字符串方法
      • 5.3 数据结构操作
    • 6. 函数式编程
      • 6.1 高阶函数
      • 6.2 迭代器
    • 7. 科学计算基础
      • 7.1 NumPy 基础
      • 7.2 数据处理
      • 7.3 线性代数
    • 8. 数据可视化
      • 8.1 Matplotlib 基础
      • 8.2 高级可视化
    • 9. 数据分析和处理
      • 9.1 Pandas 基础
      • 9.2 数据分析
    • 10. 机器学习基础
      • 10.1 Scikit-learn 入门
      • 10.2 常用算法
    • 11. 项目实践
      • 11.1 小项目练习
      • 11.2 综合项目
    • 12. 最佳实践
      • 12.1 代码规范
      • 12.2 调试和测试
      • 12.3 性能优化
    • 13. 实用技巧和常用函数
      • 13.1 常用内置函数
      • 字符和编码
      • 进制转换
      • 13.2 字符串处理技巧
      • 字符串方法
      • 字符串格式化
      • 13.3 数据结构操作
      • 列表和元组
      • 字典操作
      • 迭代器操作
      • 13.4 高级语法特性
      • 条件表达式(三元运算符)
      • 列表推导式
      • 字典推导式
      • 13.5 函数式编程工具
      • functools.reduce
      • 13.6 文件操作技巧
      • 13.7 调试和断言
      • 13.8 模块和脚本控制
      • __name__ 变量详解
      • 工作原理
      • 实际应用场景
      • 在包中的使用
      • 常见模式
      • 高级用法
      • 最佳实践
    • 14.学习资源
      • 官方文档
      • 在线教程
      • 实践项目
      • 社区资源
    • 学习路径建议
      • 初级阶段(1-2个月)
      • 中级阶段(2-3个月)
      • 高级阶段(3-6个月)
      • 专家阶段(6个月以上)
    • 常见问题
      • Q: 如何选择 Python 版本?
      • Q: 学习 Python 需要什么基础?
      • Q: 如何提高编程效率?
      • Q: 学完基础后应该学什么?
    • 总结
  • python 中的设计模式
  • module

  • tool

  • other

  • 《python》
Jacky
2023-06-01
目录

python 学习指南

# 学习目标

本大纲旨在为 Python 初学者提供系统性的学习路径,从基础语法到科学计算,逐步掌握 Python 编程技能。

# 1. Python 基础语法

# 1.1 环境搭建

  • Python 解释器安装
  • IDE 选择和配置(PyCharm, VS Code, Jupyter)
  • 虚拟环境管理(venv, conda)
  • 包管理工具(pip, conda)

# 1.2 基本概念

  • Python 简介和特点
  • 第一个 Python 程序
  • 代码注释和文档字符串
  • 代码规范和 PEP 8

# 1.3 数据类型

# 数值类型

# 整数
x = 10
y = -5

# 浮点数
pi = 3.14159
e = 2.71828

# 复数
z = 3 + 4j

# 布尔值
is_valid = True
is_error = False
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 字符串类型

# 字符串创建
name = "Python"
message = 'Hello, World!'
multi_line = """这是一个
多行字符串"""

# 字符串操作
print(len(name))           # 长度
print(name.upper())        # 转大写
print(name.lower())        # 转小写
print(name.replace('P', 'J'))  # 替换
1
2
3
4
5
6
7
8
9
10
11

# 序列类型

# 列表(可变)
my_list = [1, 2, 3, 4, 5]
my_list.append(6)          # 添加元素
my_list.remove(3)          # 删除元素
my_list[0] = 10            # 修改元素
len(my_list)               # 长度

# 元组(不可变)
my_tuple = (1, 2, 3, 4, 5)
# my_tuple[0] = 10        # 错误!元组不可修改

# 字符串(不可变)
text = "Hello"
# text[0] = 'h'           # 错误!字符串不可修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 1.4 变量和赋值

# 变量命名规则
user_name = "Alice"        # 下划线命名法
userAge = 25              # 驼峰命名法
PI = 3.14159              # 常量(约定)

# 多重赋值
a, b, c = 1, 2, 3
x = y = z = 0

# 解包赋值
numbers = [1, 2, 3]
first, second, third = numbers
1
2
3
4
5
6
7
8
9
10
11
12

# 1.5 运算符

# 算术运算符
a = 10 + 5    # 加法
b = 10 - 5    # 减法
c = 10 * 5    # 乘法
d = 10 / 5    # 除法
e = 10 // 3   # 整除
f = 10 % 3    # 取余
g = 10 ** 2   # 幂运算

# 比较运算符
x == y        # 等于
x != y        # 不等于
x > y         # 大于
x < y         # 小于
x >= y        # 大于等于
x <= y        # 小于等于

# 逻辑运算符
a and b       # 逻辑与
a or b        # 逻辑或
not a         # 逻辑非

# 成员运算符
x in list     # 包含
x not in list # 不包含
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 2. 控制流程

# 2.1 条件语句

# if 语句
if condition:
    # 执行代码
    pass

# if-else 语句
if condition:
    # 条件为真时执行
    pass
else:
    # 条件为假时执行
    pass

# if-elif-else 语句
if condition1:
    pass
elif condition2:
    pass
else:
    pass

# 条件表达式(三元运算符)
result = value_if_true if condition else value_if_false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 2.2 循环语句

# for 循环
for item in iterable:
    print(item)

# while 循环
while condition:
    # 执行代码
    pass

# 循环控制
for i in range(10):
    if i == 5:
        break       # 跳出循环
    if i == 2:
        continue    # 跳过当前迭代
    print(i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 2.3 异常处理

try:
    # 可能出错的代码
    result = 10 / 0
except ZeroDivisionError:
    # 处理特定异常
    print("除数不能为零")
except Exception as e:
    # 处理其他异常
    print(f"发生错误: {e}")
else:
    # 没有异常时执行
    print("代码执行成功")
finally:
    # 无论是否异常都执行
    print("清理工作")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 3. 函数和模块

# 3.1 函数定义

# 基本函数
def greet(name):
    """问候函数"""
    return f"Hello, {name}!"

# 带默认参数的函数
def greet_with_default(name="World"):
    return f"Hello, {name}!"

# 可变参数
def sum_numbers(*args):
    return sum(args)

# 关键字参数
def create_person(**kwargs):
    return kwargs

# 混合参数
def complex_function(a, b, *args, c=10, **kwargs):
    pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 3.2 函数高级特性

# 3.2.1 匿名函数(lambda)

# 基本用法
square = lambda x: x ** 2
print(square(5))  # 输出: 25

# 多参数
add = lambda x, y: x + y
print(add(3, 4))  # 输出: 7

# 与内置函数结合使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # 输出: [1, 4, 9, 16, 25]

# 过滤
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出: [2, 4]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 3.2.2 装饰器

# 基本装饰器
def timer(func):
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"函数执行时间: {end - start}秒")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)
    return "完成"

# 带参数的装饰器
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 CountCalls:
    def __init__(self, func):
        self.func = func
        self.count = 0
    
    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"调用次数: {self.count}")
        return self.func(*args, **kwargs)

@CountCalls
def say_hello():
    print("Hello!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

# 3.2.3 生成器(Generator)

生成器是一种特殊的迭代器,使用 yield 关键字创建。生成器函数返回一个生成器对象,可以逐个产生值,而不是一次性返回所有值。

# 生成器函数
# 基本生成器函数
def fibonacci(n):
    """生成斐波那契数列"""
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# 使用生成器
for num in fibonacci(10):
    print(num, end=' ')
# 输出: 0 1 1 2 3 5 8 13 21 34

# 转换为列表
fib_list = list(fibonacci(10))
print(fib_list)  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 生成器表达式
# 生成器表达式(类似列表推导式)
squares = (x**2 for x in range(10))
print(list(squares))  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 与函数结合使用
def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

# 使用 next() 逐个获取值
counter = count_up_to(5)
print(next(counter))  # 1
print(next(counter))  # 2
print(next(counter))  # 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 生成器的优势
# 内存效率对比
import sys

# 列表方式(占用更多内存)
def squares_list(n):
    return [x**2 for x in range(n)]

# 生成器方式(内存友好)
def squares_generator(n):
    for x in range(n):
        yield x**2

# 比较内存使用
list_squares = squares_list(1000)
gen_squares = squares_generator(1000)

print(f"列表大小: {sys.getsizeof(list_squares)} bytes")
print(f"生成器大小: {sys.getsizeof(gen_squares)} bytes")

# 输出示例:
# 列表大小: 8856 bytes
# 生成器大小: 120 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 生成器的高级用法
# 生成器链式调用
def numbers():
    for i in range(5):
        yield i

def squares(nums):
    for n in nums:
        yield n**2

def evens(nums):
    for n in nums:
        if n % 2 == 0:
            yield n

# 链式处理
result = list(evens(squares(numbers())))
print(result)  # [0, 4, 16]

# 使用 send() 向生成器发送值
def accumulator():
    total = 0
    while True:
        value = yield total
        if value is not None:
            total += value

acc = accumulator()
next(acc)  # 启动生成器
print(acc.send(10))  # 10
print(acc.send(5))   # 15
print(acc.send(3))   # 18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 生成器与迭代器的关系
# 生成器是迭代器的子类
from collections.abc import Iterator

def simple_generator():
    yield 1
    yield 2
    yield 3

gen = simple_generator()
print(isinstance(gen, Iterator))  # True

# 生成器自动实现迭代器协议
print(hasattr(gen, '__iter__'))   # True
print(hasattr(gen, '__next__'))   # True
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 3.3 模块和包

# 导入模块
import math
from math import sqrt, pi
import numpy as np
from datetime import datetime as dt

# 创建模块
# mymodule.py
def my_function():
    return "Hello from my module"

# 使用模块
import mymodule
mymodule.my_function()
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 3.4 常用模块介绍

Python 标准库包含大量实用模块,以下是常用模块及其作用:

# 基础模块

  • os - 操作系统接口,文件和目录操作
  • sys - 系统相关参数和函数
  • time - 时间相关函数
  • datetime - 日期和时间处理
  • math - 数学函数
  • random - 随机数生成
  • json - JSON 数据处理
  • pickle - 对象序列化
  • re - 正则表达式
  • collections - 特殊容器数据类型
  • itertools - 迭代器工具
  • functools - 函数式编程工具
  • inspect - 检查对象和获取源代码信息

# 文件和数据模块

  • pathlib - 面向对象的文件系统路径
  • shutil - 高级文件操作
  • glob - 文件模式匹配
  • csv - CSV 文件读写
  • xml - XML 处理
  • configparser - 配置文件解析
  • logging - 日志记录

# 网络和通信模块

  • urllib - URL 处理
  • requests - HTTP 库
  • socket - 网络编程
  • email - 邮件处理
  • smtplib - SMTP 协议
  • http - HTTP 协议
  • ssl - SSL/TLS 加密

# 并发和异步模块

  • threading - 线程管理
  • multiprocessing - 多进程
  • asyncio - 异步编程
  • concurrent.futures - 并发执行
  • queue - 队列实现
  • subprocess - 子进程管理

# 数据处理模块

  • numpy - 数值计算
  • pandas - 数据分析
  • matplotlib - 数据可视化
  • scipy - 科学计算
  • scikit-learn - 机器学习
  • seaborn - 统计可视化

# 数据库模块

  • sqlite3 - SQLite 数据库
  • pymongo - MongoDB 驱动
  • psycopg2 - PostgreSQL 驱动
  • pymysql - MySQL 驱动
  • redis - Redis 客户端

# Web 开发模块

  • flask - 轻量级 Web 框架
  • django - 全功能 Web 框架
  • fastapi - 现代 Web API 框架
  • jinja2 - 模板引擎
  • werkzeug - WSGI 工具库

# 测试模块

  • unittest - 单元测试框架
  • pytest - 测试框架
  • doctest - 文档测试
  • mock - 模拟对象
  • coverage - 代码覆盖率

# 系统管理模块

  • psutil - 系统和进程监控
  • paramiko - SSH 协议
  • fabric - 部署工具
  • ansible - 自动化配置
  • docker - Docker 容器

# 图像和多媒体模块

  • PIL/Pillow - 图像处理
  • opencv-python - 计算机视觉
  • moviepy - 视频编辑
  • pygame - 游戏开发
  • tkinter - GUI 开发

# 安全和加密模块

  • hashlib - 哈希算法
  • hmac - 消息认证
  • cryptography - 加密库
  • bcrypt - 密码哈希
  • jwt - JSON Web Token

# 其他实用模块

  • argparse - 命令行参数解析
  • click - 命令行界面
  • tqdm - 进度条
  • colorama - 终端颜色
  • pyyaml - YAML 处理
  • toml - TOML 配置
  • xlrd/xlwt - Excel 文件处理
  • openpyxl - Excel 读写
  • beautifulsoup4 - HTML/XML 解析
  • selenium - 浏览器自动化
  • scrapy - 网络爬虫框架

# 4. 面向对象编程

# 4.1 类和对象

class Person:
    """人类"""
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, I'm {self.name}"
    
    def get_age(self):
        return self.age

# 创建对象
person = Person("Alice", 25)
print(person.greet())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 4.2 继承和多态

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

# 多态
animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 4.3 特殊方法

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __len__(self):
        return int((self.x**2 + self.y**2)**0.5)
1
2
3
4
5
6
7
8
9
10
11
12
13

# 4.3.1 装饰器(Decorators)

装饰器是Python中的高级特性,用于修改或增强函数和类的行为。

# @property 装饰器

@property 将方法转换为属性访问,提供更优雅的API。

class Circle:
    """圆类,使用 @property"""
    
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        """获取半径"""
        return self._radius
    
    @radius.setter
    def radius(self, value):
        """设置半径"""
        if value < 0:
            raise ValueError("半径不能为负数")
        self._radius = value
    
    @property
    def area(self):
        """计算面积(只读属性)"""
        import math
        return math.pi * self._radius ** 2
    
    @property
    def circumference(self):
        """计算周长(只读属性)"""
        import math
        return 2 * math.pi * self._radius

# 使用示例
circle = Circle(5)
print(circle.radius)      # 5 - 像访问属性一样
print(circle.area)        # 78.54 - 自动计算
circle.radius = 10        # 使用setter修改
# circle.area = 100       # 错误!area是只读的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

# @dataclass 装饰器(Python 3.7+)

@dataclass 自动生成常用的特殊方法,简化类的定义。

from dataclasses import dataclass, field
from typing import List

# 基本用法
@dataclass
class Person:
    """人员信息类"""
    name: str
    age: int
    email: str
    
    # 自动生成:__init__, __repr__, __eq__ 等方法

# 使用示例
person1 = Person("Alice", 25, "[email protected]")
person2 = Person("Alice", 25, "[email protected]")

print(person1)                # Person(name='Alice', age=25, email='[email protected]')
print(person1 == person2)     # True - 自动实现__eq__

# 高级用法
@dataclass(order=True, frozen=False)
class Student:
    """学生类"""
    name: str
    student_id: int
    grade: float = 0.0  # 默认值
    courses: List[str] = field(default_factory=list)  # 可变默认值
    
    def __post_init__(self):
        """初始化后的处理"""
        if self.grade < 0 or self.grade > 100:
            raise ValueError("成绩必须在0-100之间")

# 使用示例
student = Student("Bob", 12345, 85.5, ["Math", "Physics"])
print(student)

# 排序(因为 order=True)
students = [
    Student("Alice", 1001, 90.0),
    Student("Bob", 1002, 85.0),
    Student("Charlie", 1003, 95.0)
]
sorted_students = sorted(students, key=lambda s: s.grade, reverse=True)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

@dataclass 参数详解:

参数 默认值 说明
init True 生成 __init__ 方法
repr True 生成 __repr__ 方法
eq True 生成 __eq__ 方法
order False 生成 __lt__, __le__, __gt__, __ge__ 方法
frozen False 使实例不可变(类似元组)
# frozen=True 示例
@dataclass(frozen=True)
class ImmutablePoint:
    """不可变的点"""
    x: float
    y: float

point = ImmutablePoint(1.0, 2.0)
# point.x = 3.0  # 错误!frozen 对象不可修改
1
2
3
4
5
6
7
8
9

# @staticmethod 和 @classmethod 装饰器

class MathOperations:
    """数学运算类"""
    
    pi = 3.14159
    
    def __init__(self, base):
        self.base = base
    
    @staticmethod
    def add(a, b):
        """静态方法:不需要访问实例或类"""
        return a + b
    
    @classmethod
    def from_string(cls, value_str):
        """类方法:接收类作为第一个参数"""
        value = float(value_str)
        return cls(value)
    
    @classmethod
    def get_pi(cls):
        """访问类属性"""
        return cls.pi
    
    def instance_method(self, value):
        """实例方法:访问实例属性"""
        return self.base + value

# 使用示例
print(MathOperations.add(3, 5))              # 8 - 直接调用静态方法
obj = MathOperations.from_string("10.5")     # 使用类方法创建实例
print(obj.base)                              # 10.5
print(MathOperations.get_pi())               # 3.14159
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# @functools.lru_cache 装饰器

@lru_cache 提供函数结果缓存,提高性能。

from functools import lru_cache
import time

# 不使用缓存
def fibonacci_slow(n):
    """慢速斐波那契(递归,无缓存)"""
    if n <= 1:
        return n
    return fibonacci_slow(n-1) + fibonacci_slow(n-2)

# 使用缓存
@lru_cache(maxsize=128)
def fibonacci_fast(n):
    """快速斐波那契(递归,有缓存)"""
    if n <= 1:
        return n
    return fibonacci_fast(n-1) + fibonacci_fast(n-2)

# 性能对比
start = time.time()
result1 = fibonacci_slow(30)
print(f"无缓存耗时: {time.time() - start:.4f}秒")

start = time.time()
result2 = fibonacci_fast(30)
print(f"有缓存耗时: {time.time() - start:.4f}秒")

# 查看缓存信息
print(fibonacci_fast.cache_info())  # CacheInfo(hits=28, misses=31, maxsize=128, currsize=31)

# 清空缓存
fibonacci_fast.cache_clear()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# 自定义装饰器

# 基础装饰器
def timer(func):
    """计时装饰器"""
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行时间: {end - start:.4f}秒")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)
    return "完成"

# 带参数的装饰器
def repeat(times):
    """重复执行装饰器"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            results = []
            for _ in range(times):
                result = func(*args, **kwargs)
                results.append(result)
            return results
        return wrapper
    return decorator

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

print(greet("Alice"))  # ['Hello, Alice!', 'Hello, Alice!', 'Hello, Alice!']

# 类装饰器
class CountCalls:
    """统计函数调用次数的装饰器"""
    
    def __init__(self, func):
        self.func = func
        self.count = 0
    
    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"{self.func.__name__} 被调用了 {self.count} 次")
        return self.func(*args, **kwargs)

@CountCalls
def process_data(data):
    return data * 2

process_data(5)   # process_data 被调用了 1 次
process_data(10)  # process_data 被调用了 2 次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

# 常用内置装饰器

from abc import ABC, abstractmethod

class Animal(ABC):
    """抽象基类"""
    
    @abstractmethod
    def speak(self):
        """抽象方法"""
        pass
    
    @property
    def species(self):
        """属性方法"""
        return self.__class__.__name__
    
    @staticmethod
    def is_animal():
        """静态方法"""
        return True
    
    @classmethod
    def create_default(cls):
        """类方法"""
        return cls()

class Dog(Animal):
    def speak(self):
        return "Woof!"

# 使用示例
dog = Dog()
print(dog.speak())         # Woof!
print(dog.species)         # Dog
print(Dog.is_animal())     # True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# 装饰器最佳实践

from functools import wraps

# 1. 使用 @wraps 保留函数元信息
def my_decorator(func):
    @wraps(func)  # 保留原函数的名称、文档字符串等
    def wrapper(*args, **kwargs):
        print(f"调用 {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def greet(name):
    """问候函数"""
    return f"Hello, {name}"

print(greet.__name__)  # greet(不是wrapper)
print(greet.__doc__)   # 问候函数

# 2. 装饰器叠加
@timer
@lru_cache(maxsize=128)
def expensive_function(n):
    """复杂计算"""
    import time
    time.sleep(0.1)
    return n ** 2

# 3. 条件装饰器
def conditional_decorator(condition):
    def decorator(func):
        if condition:
            @wraps(func)
            def wrapper(*args, **kwargs):
                print("条件满足,执行装饰")
                return func(*args, **kwargs)
            return wrapper
        else:
            return func
    return decorator

DEBUG = True

@conditional_decorator(DEBUG)
def debug_function():
    print("函数执行")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

# 4.4 基类和元类

# 基类(Base Class)

基类 是被其他类继承的类,也称为父类或超类。基类定义了子类可以继承的属性和方法。

# 基类定义
class Animal:
    """动物基类"""
    
    def __init__(self, name, species):
        self.name = name
        self.species = species
    
    def speak(self):
        """说话方法(基类方法)"""
        return f"{self.name} 发出声音"
    
    def get_info(self):
        """获取信息"""
        return f"名称: {self.name}, 物种: {self.species}"

# 子类继承基类
class Dog(Animal):
    """狗类,继承自Animal"""
    
    def __init__(self, name, breed):
        # 调用父类的__init__方法
        super().__init__(name, "犬科")
        self.breed = breed
    
    def speak(self):
        """重写父类的speak方法"""
        return f"{self.name} 汪汪叫"
    
    def fetch(self):
        """狗特有的方法"""
        return f"{self.name} 在捡球"

# 使用示例
dog = Dog("旺财", "金毛")
print(dog.speak())      # 旺财 汪汪叫
print(dog.get_info())   # 名称: 旺财, 物种: 犬科
print(dog.fetch())      # 旺财 在捡球
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

# 抽象基类(Abstract Base Class)

抽象基类 是不能被直接实例化的基类,用于定义接口和强制子类实现特定方法。

from abc import ABC, abstractmethod

class Shape(ABC):
    """形状抽象基类"""
    
    def __init__(self, name):
        self.name = name
    
    @abstractmethod
    def area(self):
        """计算面积(抽象方法)"""
        pass
    
    @abstractmethod
    def perimeter(self):
        """计算周长(抽象方法)"""
        pass
    
    def get_name(self):
        """获取形状名称"""
        return self.name

class Circle(Shape):
    """圆形类"""
    
    def __init__(self, radius):
        super().__init__("圆形")
        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

class Rectangle(Shape):
    """矩形类"""
    
    def __init__(self, width, height):
        super().__init__("矩形")
        self.width = width
        self.height = height
    
    def area(self):
        """实现面积计算"""
        return self.width * self.height
    
    def perimeter(self):
        """实现周长计算"""
        return 2 * (self.width + self.height)

# 使用示例
circle = Circle(5)
rectangle = Rectangle(4, 6)

print(f"{circle.get_name()}: 面积={circle.area():.2f}, 周长={circle.perimeter():.2f}")
print(f"{rectangle.get_name()}: 面积={rectangle.area()}, 周长={rectangle.perimeter()}")

# 尝试实例化抽象基类会报错
# shape = Shape("形状")  # TypeError: Can't instantiate abstract class Shape
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

# 元类(Metaclass)

元类 是创建类的类。在Python中,类本身也是对象,而元类就是创建这些类对象的类。

# 基本概念
# 所有类都是type的实例
print(type(int))        # <class 'type'>
print(type(str))        # <class 'type'>
print(type(list))       # <class 'type'>

# 自定义类也是type的实例
class MyClass:
    pass

print(type(MyClass))    # <class 'type'>

# type是type的实例
print(type(type))       # <class 'type'>
1
2
3
4
5
6
7
8
9
10
11
12
13
# 使用type创建类
# 使用type动态创建类
def __init__(self, name):
    self.name = name

def greet(self):
    return f"Hello, {self.name}!"

# 创建类
Person = type('Person', (), {
    '__init__': __init__,
    'greet': greet,
    'species': 'Human'
})

# 使用创建的类
person = Person("Alice")
print(person.greet())    # Hello, Alice!
print(person.species)    # Human
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 自定义元类
class MetaLogger(type):
    """记录类创建的元类"""
    
    def __new__(cls, name, bases, namespace):
        print(f"创建类: {name}")
        print(f"基类: {bases}")
        print(f"命名空间: {list(namespace.keys())}")
        
        # 添加创建时间
        namespace['created_at'] = '2024-01-01'
        
        return super().__new__(cls, name, bases, namespace)

class MyClass(metaclass=MetaLogger):
    """使用自定义元类的类"""
    
    def __init__(self):
        self.value = 42
    
    def get_value(self):
        return self.value

# 输出:
# 创建类: MyClass
# 基类: ()
# 命名空间: ['__module__', '__qualname__', '__init__', 'get_value']

obj = MyClass()
print(obj.get_value())   # 42
print(obj.created_at)    # 2024-01-01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 元类的实际应用
class Singleton(type):
    """单例模式元类"""
    
    _instances = {}
    
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class Database(metaclass=Singleton):
    """数据库连接类(单例)"""
    
    def __init__(self):
        self.connection = "数据库连接"
    
    def query(self, sql):
        return f"执行查询: {sql}"

# 测试单例
db1 = Database()
db2 = Database()
print(db1 is db2)        # True
print(db1.query("SELECT * FROM users"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 属性验证元类
class ValidatedMeta(type):
    """属性验证元类"""
    
    def __new__(cls, name, bases, namespace):
        # 检查是否有验证规则
        if 'fields' in namespace:
            fields = namespace['fields']
            
            def __init__(self, **kwargs):
                for field_name, field_type in fields.items():
                    if field_name in kwargs:
                        value = kwargs[field_name]
                        if not isinstance(value, field_type):
                            raise TypeError(f"{field_name} 必须是 {field_type.__name__} 类型")
                        setattr(self, field_name, value)
                    else:
                        raise ValueError(f"缺少必需字段: {field_name}")
            
            namespace['__init__'] = __init__
        
        return super().__new__(cls, name, bases, namespace)

class User(metaclass=ValidatedMeta):
    """用户类,使用验证元类"""
    
    fields = {
        'name': str,
        'age': int,
        'email': str
    }

# 使用示例
try:
    user = User(name="Alice", age=25, email="[email protected]")
    print(f"用户创建成功: {user.name}, {user.age}岁")
    
    # 类型错误
    user2 = User(name="Bob", age="30", email="[email protected]")
except TypeError as e:
    print(f"类型错误: {e}")
except ValueError as e:
    print(f"值错误: {e}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 自动注册元类
class RegistryMeta(type):
    """自动注册元类"""
    
    _registry = {}
    
    def __new__(cls, name, bases, namespace):
        # 创建类
        new_class = super().__new__(cls, name, bases, namespace)
        
        # 注册到字典中
        if name not in cls._registry:
            cls._registry[name] = new_class
        
        return new_class
    
    @classmethod
    def get_class(cls, name):
        """根据名称获取类"""
        return cls._registry.get(name)
    
    @classmethod
    def list_classes(cls):
        """列出所有注册的类"""
        return list(cls._registry.keys())

class Animal(metaclass=RegistryMeta):
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

# 查看注册的类
print(RegistryMeta.list_classes())  # ['Animal', 'Dog', 'Cat']
print(RegistryMeta.get_class('Dog'))  # <class '__main__.Dog'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 元类的高级用法
class CachedMeta(type):
    """缓存元类,为类方法添加缓存功能"""
    
    def __new__(cls, name, bases, namespace):
        # 为所有方法添加缓存
        for key, value in namespace.items():
            if callable(value) and not key.startswith('_'):
                # 创建缓存版本的方法
                cached_method = cls._create_cached_method(value)
                namespace[key] = cached_method
        
        return super().__new__(cls, name, bases, namespace)
    
    @staticmethod
    def _create_cached_method(method):
        """创建缓存方法"""
        cache = {}
        
        def cached_method(*args, **kwargs):
            # 创建缓存键
            key = str(args) + str(sorted(kwargs.items()))
            
            if key not in cache:
                cache[key] = method(*args, **kwargs)
            
            return cache[key]
        
        return cached_method

class Calculator(metaclass=CachedMeta):
    """计算器类,方法自动缓存"""
    
    def fibonacci(self, n):
        """计算斐波那契数(递归,性能较差)"""
        if n <= 1:
            return n
        return self.fibonacci(n-1) + self.fibonacci(n-2)
    
    def factorial(self, n):
        """计算阶乘"""
        if n <= 1:
            return 1
        return n * self.factorial(n-1)

# 使用示例
calc = Calculator()
print(calc.fibonacci(10))  # 快速返回,因为有缓存
print(calc.factorial(5))   # 快速返回,因为有缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

# 4.5 元类和基类的最佳实践

# 1. 优先使用组合而不是继承
class Engine:
    def start(self):
        return "引擎启动"

class Car:
    def __init__(self):
        self.engine = Engine()  # 组合
    
    def start(self):
        return self.engine.start()

# 2. 使用抽象基类定义接口
from abc import ABC, abstractmethod

class DataProcessor(ABC):
    @abstractmethod
    def process(self, data):
        pass
    
    @abstractmethod
    def validate(self, data):
        pass

# 3. 谨慎使用元类
# 元类增加了代码复杂性,只在必要时使用

# 4. 使用描述符进行属性管理
class ValidatedAttribute:
    def __init__(self, min_value=None, max_value=None):
        self.min_value = min_value
        self.max_value = max_value
    
    def __get__(self, instance, owner):
        return instance.__dict__.get(self.name)
    
    def __set__(self, instance, value):
        if self.min_value is not None and value < self.min_value:
            raise ValueError(f"值不能小于 {self.min_value}")
        if self.max_value is not None and value > self.max_value:
            raise ValueError(f"值不能大于 {self.max_value}")
        instance.__dict__[self.name] = value
    
    def __set_name__(self, owner, name):
        self.name = name

class Product:
    price = ValidatedAttribute(min_value=0)
    quantity = ValidatedAttribute(min_value=0, max_value=1000)
    
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

# 5. 数据处理基础

# 5.1 文件操作

# 文件读写
with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

with open('output.txt', 'w', encoding='utf-8') as f:
    f.write("Hello, World!")

# 逐行读取
with open('file.txt', 'r') as f:
    for line in f:
        print(line.strip())
1
2
3
4
5
6
7
8
9
10
11

# 5.2 字符串处理

# 5.2.1 字符串切片 (String Slicing)

字符串切片是Python中处理字符串的重要技术,语法格式为:s[start:stop:step]

# 基本切片语法
text = "Hello, World!"
print(text[0:5])      # "Hello" - 从索引0到4(不包含5)
print(text[7:12])     # "World" - 从索引7到11
print(text[:5])       # "Hello" - 从开始到索引4
print(text[7:])       # "World!" - 从索引7到结尾
print(text[:])        # "Hello, World!" - 整个字符串

# 负索引切片
print(text[-6:])      # "World!" - 从倒数第6个字符到结尾
print(text[-6:-1])    # "World" - 从倒数第6个到倒数第2个
print(text[:-7])      # "Hello," - 从开始到倒数第7个字符

# 步长切片
print(text[::2])      # "Hlo ol!" - 每隔一个字符
print(text[1::2])     # "el,Wrd" - 从索引1开始,每隔一个字符
print(text[::-1])     # "!dlroW ,olleH" - 反转字符串
print(text[::3])      # "Hl r!" - 每隔两个字符

# 常用切片模式
s = "abcdefghijklmnopqrstuvwxyz"

# 获取前N个字符
print(s[:3])          # "abc"

# 获取后N个字符  
print(s[-3:])         # "xyz"

# 去掉前N个字符
print(s[3:])          # "defghijklmnopqrstuvwxyz"

# 去掉后N个字符
print(s[:-3])         # "abcdefghijklmnopqrstuvw"

# 每隔N个字符取一个
print(s[::2])         # "acegikmoqsuwy"

# 反转字符串
print(s[::-1])        # "zyxwvutsrqponmlkjihgfedcba"

# 实际应用示例
filename = "document.pdf"
name = filename[:-4]  # "document" - 去掉扩展名
extension = filename[-3:]  # "pdf" - 获取扩展名

# 处理文件路径
path = "/home/user/documents/file.txt"
directory = path[:path.rfind('/')]  # "/home/user/documents"
filename = path[path.rfind('/')+1:]  # "file.txt"

# 数据清洗
data = "  123,456,789  "
clean_data = data.strip()  # "123,456,789"
numbers = clean_data.split(',')  # ['123', '456', '789']

# 提取特定模式
url = "https://www.example.com/page"
protocol = url[:url.find('://')]  # "https"
domain = url[url.find('://')+3:url.find('/', 8)]  # "www.example.com"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

# 5.2.2 字符串方法

# 字符串方法
text = "  Hello, World!  "
print(text.strip())        # 去除首尾空格
print(text.split(','))     # 分割字符串
print(text.replace('World', 'Python'))  # 替换

# 字符串格式化
name = "Alice"
age = 25
print(f"{name} is {age} years old")
print("{} is {} years old".format(name, age))
1
2
3
4
5
6
7
8
9
10
11

# 5.3 数据结构操作

# 列表推导式
squares = [x**2 for x in range(10)]
#   遍历 range(10) 中的每个元素(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
#   条件判断:对每个元素 x,检查 x % 2 == 0(即是否为偶数)
#   选择性处理:只有当条件为 True 时,才计算 x**2 并加入结果列表
even_squares = [x**2 for x in range(10) if x % 2 == 0]

# 字典推导式
word_lengths = {word: len(word) for word in ['apple', 'banana', 'cherry']}

# 生成器表达式
sum_squares = sum(x**2 for x in range(1000000))
1
2
3
4
5
6
7
8
9
10
11
12

# 6. 函数式编程

# 6.1 高阶函数

# map 函数
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))

# filter 函数
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

# reduce 函数
from functools import reduce
sum_all = reduce(lambda x, y: x + y, numbers)
1
2
3
4
5
6
7
8
9
10

# 6.2 迭代器

迭代器是一个实现了 __iter__() 和 __next__() 方法的对象。迭代器允许我们逐个访问集合中的元素,而不需要一次性加载所有元素到内存中。

# 自定义迭代器
class CountDown:
    def __init__(self, start):
        self.start = start
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.start <= 0:
            raise StopIteration
        self.start -= 1
        return self.start + 1

# 使用迭代器
countdown = CountDown(5)
for num in countdown:
    print(num, end=' ')
# 输出: 5 4 3 2 1

# 手动使用迭代器
countdown2 = CountDown(3)
iterator = iter(countdown2)
print(next(iterator))  # 3
print(next(iterator))  # 2
print(next(iterator))  # 1
# print(next(iterator))  # 抛出 StopIteration 异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

提示

生成器的详细内容请参考 3.2.3 生成器(Generator) 章节。

# 7. 科学计算基础

# 7.1 NumPy 基础

import numpy as np

# 数组创建
arr = np.array([1, 2, 3, 4, 5])
zeros = np.zeros((3, 3))
ones = np.ones((2, 4))
random_arr = np.random.rand(3, 3)

# 数组操作
print(arr.shape)           # 形状
print(arr.dtype)           # 数据类型
print(arr.reshape(5, 1))   # 重塑形状
1
2
3
4
5
6
7
8
9
10
11
12

# 7.2 数据处理

# 数组索引和切片
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[0, 1])           # 单个元素
print(arr[1:, :2])         # 切片

# 数学运算
print(np.mean(arr))        # 平均值
print(np.std(arr))         # 标准差
print(np.sum(arr))         # 总和
1
2
3
4
5
6
7
8
9

# 7.3 线性代数

# 矩阵运算
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

print(np.dot(A, B))        # 矩阵乘法
print(np.linalg.inv(A))    # 矩阵求逆
print(np.linalg.eig(A))    # 特征值和特征向量
1
2
3
4
5
6
7

# 8. 数据可视化

# 8.1 Matplotlib 基础

import matplotlib.pyplot as plt
import numpy as np

# 基本绘图
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13

# 8.2 高级可视化

# 子图
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

ax1.plot(x, np.sin(x))
ax1.set_title('Sine')

ax2.plot(x, np.cos(x))
ax2.set_title('Cosine')

plt.tight_layout()
plt.show()
1
2
3
4
5
6
7
8
9
10
11

# 9. 数据分析和处理

# 9.1 Pandas 基础

import pandas as pd

# 创建 DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'London', 'Paris']
}
df = pd.DataFrame(data)

# 数据操作
print(df.head())           # 查看前几行
print(df.describe())       # 描述性统计
print(df['Age'].mean())    # 列平均值
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 9.2 数据分析

# 数据过滤
young_people = df[df['Age'] < 30]

# 数据聚合
age_stats = df.groupby('City')['Age'].agg(['mean', 'std', 'count'])

# 数据透视表
pivot_table = df.pivot_table(values='Age', index='City', aggfunc='mean')
1
2
3
4
5
6
7
8

# 10. 机器学习基础

# 10.1 Scikit-learn 入门

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import numpy as np

# 准备数据
X = np.random.rand(100, 1)
y = 2 * X + 1 + 0.1 * np.random.randn(100, 1)

# 分割数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# 训练模型
model = LinearRegression()
model.fit(X_train, y_train)

# 预测和评估
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f"均方误差: {mse}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 10.2 常用算法

# 分类算法
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC

# 回归算法
from sklearn.linear_model import Ridge, Lasso
from sklearn.ensemble import RandomForestRegressor

# 聚类算法
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
1
2
3
4
5
6
7
8
9
10
11

# 11. 项目实践

# 11.1 小项目练习

# 计算器程序
def calculator():
    while True:
        try:
            expression = input("请输入表达式 (q退出): ")
            if expression.lower() == 'q':
                break
            result = eval(expression)
            print(f"结果: {result}")
        except Exception as e:
            print(f"错误: {e}")

# 文件批量处理
import os
def batch_rename(directory, prefix):
    for filename in os.listdir(directory):
        if filename.endswith('.txt'):
            new_name = f"{prefix}_{filename}"
            os.rename(os.path.join(directory, filename),
                     os.path.join(directory, new_name))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 11.2 综合项目

# 数据分析项目
import pandas as pd
import matplotlib.pyplot as plt

def analyze_sales_data(file_path):
    # 读取数据
    df = pd.read_csv(file_path)
    
    # 数据清洗
    df = df.dropna()
    
    # 数据分析
    monthly_sales = df.groupby(df['date'].dt.month)['sales'].sum()
    
    # 可视化
    plt.figure(figsize=(10, 6))
    monthly_sales.plot(kind='bar')
    plt.title('月度销售统计')
    plt.xlabel('月份')
    plt.ylabel('销售额')
    plt.show()
    
    return monthly_sales
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 12. 最佳实践

# 12.1 代码规范


# PEP 8 规范示例
def calculate_area(length, width):
    """计算矩形面积
    
    Args:
        length (float): 长度
        width (float): 宽度
    
    Returns:
        float: 面积
    """
    return length * width

# 变量命名
user_name = "Alice"        # 下划线命名法
MAX_RETRY_COUNT = 3        # 常量使用大写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 12.2 调试和测试

# 调试技巧
import pdb

def debug_function():
    x = 10
    pdb.set_trace()  # 设置断点
    y = x * 2
    return y

# 单元测试
import unittest

class TestCalculator(unittest.TestCase):
    def test_add(self):
        self.assertEqual(2 + 2, 4)
    
    def test_multiply(self):
        self.assertEqual(3 * 4, 12)

if __name__ == '__main__':
    unittest.main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 12.3 性能优化

# 性能分析
import time
import cProfile

def profile_function(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"执行时间: {end_time - start_time}秒")
        return result
    return wrapper

@profile_function
def slow_function():
    import time
    time.sleep(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 13. 实用技巧和常用函数

# 13.1 常用内置函数

# 字符和编码

# 获取字符的ASCII编码
ord('M')  # 返回 77

# 获取ASCII编码对应的字符
chr(77)   # 返回 'M'
1
2
3
4
5

# 进制转换

# 字符串转数字(指定进制)
int('19', 16)    # 将 '19' 视为十六进制,转换为十进制 25

# 数字转不同进制字符串
format(19, 'b')  # 转二进制,返回 '10011'
format(19, 'o')  # 转八进制,返回 '23'
format(19, 'x')  # 转十六进制,返回 '13'

# 使用内置函数
bin(19)          # 转二进制,返回 '0b10011'
oct(19)          # 转八进制,返回 '0o23'
hex(19)          # 转十六进制,返回 '0x13'

# 使用f-string格式化
print(f"{19:b}") # 输出二进制 '10011'
print(f"{19:o}") # 输出八进制 '23'
print(f"{19:x}") # 输出十六进制 '13'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 13.2 字符串处理技巧

# 字符串方法

# 连接字符串
words = ['Hello', 'World', 'Python']
result = ' '.join(words)  # 'Hello World Python'

# 分割字符串
text = "apple,banana,cherry"
fruits = text.split(',')  # ['apple', 'banana', 'cherry']

# 去除空白字符
text = "  Hello World  "
cleaned = text.strip()    # 去除首尾空格
left_cleaned = text.lstrip()  # 去除左侧空格
right_cleaned = text.rstrip() # 去除右侧空格
1
2
3
4
5
6
7
8
9
10
11
12
13

# 字符串格式化

# f-string(推荐)
name = 'Alice'
age = 25
print(f'{name} is {age} years old')

# str.format()方法
print('{} is {} years old'.format(name, age))

# 旧式格式化(%操作符)
print('The value of pi is approximately %.3f.' % 3.14159)
1
2
3
4
5
6
7
8
9
10

# 13.3 数据结构操作

# 列表和元组

# 列表操作
my_list = [1, 2, 3]

# 添加元素
my_list.append(4)                    # 添加单个元素
my_list.extend([5, 6, 7])           # 添加多个元素
my_list += [8, 9]                   # 等价于extend

# 删除元素
del my_list[1:]                     # 删除指定范围
del my_list[:]                      # 清空列表
my_list.clear()                     # 清空列表

# 检查元素
len(my_list)                        # 获取长度
2 in my_list                        # 检查包含
2 not in my_list                    # 检查不包含

# 元组(不可变)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10                 # 错误!元组不可修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 字典操作

# 创建和更新字典
my_dict = {"a": 1, "b": 2}

# 直接赋值
my_dict["c"] = 3

# 使用update方法合并字典
other_dict = {"d": 4, "e": 5}
my_dict.update(other_dict)

# 使用构造函数
new_dict = dict(a=1, b=2, c=3)

# 字典推导式
doubled = {k: v * 2 for k, v in my_dict.items()}

# 安全添加键值对
my_dict.setdefault("f", 6)  # 如果键不存在则添加

# 批量创建字典
keys = ["x", "y", "z"]
default_dict = dict.fromkeys(keys, 0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 迭代器操作

# 使用enumerate获取索引
for index, key in enumerate(my_dict):
    print(f'{index}: {key} = {my_dict[key]}')

# 遍历字典
for key, value in my_dict.items():
    print(f"{key}: {value}")

# 只遍历键
for key in my_dict:
    print(key)

# 只遍历值
for value in my_dict.values():
    print(value)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 13.4 高级语法特性

# 条件表达式(三元运算符)

# 基本语法
result = value_if_true if condition else value_if_false

# 实际应用
x = 10
y = 20
max_value = x if x > y else y

# 复杂条件
device = frida.get_usb_device() if device is None else device
1
2
3
4
5
6
7
8
9
10

# 列表推导式

# 基本语法
[expression for item in iterable if condition]

# 简单示例
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

# 实际应用
import os
for root, dirs, files in os.walk(directory):
    # 过滤目录
    dirs[:] = [d for d in dirs if not d.startswith('.')]
    
    # 过滤文件
    files[:] = [f for f in files if f.endswith('.txt')]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 字典推导式

# 基本语法
{key_expression: value_expression for item in iterable if condition}

# 键值对反转
vocab = {"apple": 1, "banana": 2, "cherry": 3}
int_to_str = {i: s for s, i in vocab.items()}
# 结果: {1: "apple", 2: "banana", 3: "cherry"}

# 值转换
doubled = {k: v * 2 for k, v in vocab.items()}
1
2
3
4
5
6
7
8
9
10

# 13.5 函数式编程工具

# functools.reduce

from functools import reduce

# 累积求和
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)  # 15

# 累积求积
product = reduce(lambda x, y: x * y, numbers)  # 120

# 自定义函数
def add(x, y):
    return x + y

result = reduce(add, numbers)  # 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 13.6 文件操作技巧

# 文件读写
with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# 二进制文件操作
with open('output.html', 'wb') as f:
    f.write(response.text.encode('utf-8'))

# 逐行处理
with open('file.txt', 'r') as f:
    for line in f:
        print(line.strip())
1
2
3
4
5
6
7
8
9
10
11
12

# 13.7 调试和断言

# 断言语句
assert condition, "错误信息"

# 实际应用
try:
    device = frida.get_usb_device() if device is None else device
except:
    device = frida.get_remote_device() if device is None else device

assert device, "Unable to connect android device"

# 调试断点
import pdb

def debug_function():
    x = 10
    pdb.set_trace()  # 设置断点
    y = x * 2
    return y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 13.8 模块和脚本控制

# __name__ 变量详解

__name__ 是Python中的一个特殊内置变量,用于判断当前模块是被直接运行还是被导入。

# 基本用法
if __name__ == '__main__':
    # 当脚本被直接运行时执行的代码
    print("这个脚本被直接运行")
else:
    # 当脚本被导入时执行的代码
    print("这个脚本被导入为模块")
1
2
3
4
5
6
7

# 工作原理

  1. 直接运行脚本时:__name__ 的值为 '__main__'
  2. 作为模块导入时:__name__ 的值为模块名
# example.py
def greet(name):
    return f"Hello, {name}!"

def main():
    print("这是主程序")
    print(greet("World"))

# 只有直接运行此文件时才执行main函数
if __name__ == '__main__':
    main()
1
2
3
4
5
6
7
8
9
10
11

# 实际应用场景

# 模块文件:utils.py
def calculate_area(length, width):
    """计算矩形面积"""
    return length * width

def calculate_perimeter(length, width):
    """计算矩形周长"""
    return 2 * (length + width)

# 测试代码
def test_functions():
    """测试函数"""
    assert calculate_area(5, 3) == 15
    assert calculate_perimeter(5, 3) == 16
    print("所有测试通过!")

# 只有直接运行此文件时才执行测试
if __name__ == '__main__':
    test_functions()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 在包中的使用

# 包的主入口:__main__.py
from . import module1, module2

def main():
    """包的主函数"""
    print("包被直接运行")
    module1.function1()
    module2.function2()

if __name__ == '__main__':
    main()
1
2
3
4
5
6
7
8
9
10
11

# 常见模式

# 1. 主程序入口
if __name__ == '__main__':
    main()

# 2. 测试代码
if __name__ == '__main__':
    import unittest
    unittest.main()

# 3. 命令行工具
if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        process_file(sys.argv[1])
    else:
        print("请提供文件名")

# 4. 配置检查
if __name__ == '__main__':
    check_config()
    start_server()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 高级用法

# 条件导入
if __name__ == '__main__':
    # 只在直接运行时导入某些模块
    import matplotlib.pyplot as plt
    import numpy as np

# 性能测试
if __name__ == '__main__':
    import time
    start_time = time.time()
    # 执行测试代码
    end_time = time.time()
    print(f"执行时间: {end_time - start_time}秒")
1
2
3
4
5
6
7
8
9
10
11
12
13

# 最佳实践

  1. 将可重用代码放在 if __name__ == '__main__': 之外
  2. 将测试代码放在 if __name__ == '__main__': 之内
  3. 使用 main() 函数封装主要逻辑
  4. 避免在模块级别执行副作用操作
# 好的做法
def main():
    """主函数"""
    # 主要逻辑
    pass

def test():
    """测试函数"""
    # 测试逻辑
    pass

if __name__ == '__main__':
    main()
    test()

# 避免的做法
print("这会在导入时执行")  # 不好

if __name__ == '__main__':
    print("这只在直接运行时执行")  # 好
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 14.学习资源

# 官方文档

  • Python 官方教程 (opens new window)
  • Python 标准库 (opens new window)
  • PEP 8 代码规范 (opens new window)

# 在线教程

  • W3Schools Python (opens new window)
  • Real Python (opens new window)
  • Python for Everybody (opens new window)

# 实践项目

  • Python 项目集合 (opens new window)
  • Python 脚本库 (opens new window)
  • Python 学习笔记 (opens new window)

# 社区资源

  • Python 官方论坛 (opens new window)
  • Stack Overflow (opens new window)
  • Reddit r/Python (opens new window)

# 学习路径建议

# 初级阶段(1-2个月)

  1. 掌握 Python 基础语法
  2. 熟悉数据类型和控制流程
  3. 学会函数定义和模块使用
  4. 完成基础项目练习

# 中级阶段(2-3个月)

  1. 深入学习面向对象编程
  2. 掌握函数式编程概念
  3. 学习数据处理和文件操作
  4. 开始使用 NumPy 和 Pandas

# 高级阶段(3-6个月)

  1. 学习数据可视化
  2. 掌握机器学习基础
  3. 完成综合项目
  4. 学习代码优化和测试

# 专家阶段(6个月以上)

  1. 深入研究特定领域
  2. 参与开源项目
  3. 学习高级框架和工具
  4. 持续学习和实践

# 常见问题

# Q: 如何选择 Python 版本?

A: 建议使用 Python 3.8+ 版本,它提供了更好的性能和功能。

# Q: 学习 Python 需要什么基础?

A: 基本的计算机操作能力即可,Python 语法简单易学。

# Q: 如何提高编程效率?

A: 多练习、多阅读优秀代码、使用合适的 IDE 和工具。

# Q: 学完基础后应该学什么?

A: 根据兴趣选择方向:Web 开发、数据分析、机器学习、自动化等。

# 总结

Python 是一门强大而灵活的编程语言,适合初学者入门,也适合专业开发。通过系统性的学习和持续的实践,您可以掌握 Python 编程技能,并在各个领域发挥其优势。

记住:编程是一门实践的艺术,多写代码、多调试、多思考,才能真正掌握 Python 编程。

#Python#tutorial
上次更新: 2025/10/09, 23:53:03
python 中的设计模式

python 中的设计模式→

最近更新
01
npx 使用指南
10-12
02
cursor
09-28
03
inspect
07-20
更多文章>
Theme by Vdoing | Copyright © 2019-2025 Jacky | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式