python 学习之基础增强教程

以下是Python基础增强教程的进阶知识点整理,帮助巩固核心概念并提升编码能力:


一、Python高级特性

1. 列表推导式 & 生成器

python 复制代码
# 列表推导式(快速生成列表)
squares = [x**2 for x in range(10) if x % 2 == 0]  # [0,4,16,36,64]

# 生成器(节省内存)
gen = (x**2 for x in range(100000))  # 惰性计算

2. 装饰器(函数增强)

python 复制代码
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"耗时: {time.time()-start:.2f}s")
        return result
    return wrapper

@timer
def my_function():
    time.sleep(1)

3. 上下文管理器(资源管理)

python 复制代码
# 使用 with 自动关闭文件
with open('data.txt', 'r') as f:
    content = f.read()

# 自定义上下文管理器
class DatabaseConnection:
    def __enter__(self):
        self.conn = connect_db()
        return self.conn
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.close()

二、面向对象编程深入

1. 继承与多态

python 复制代码
class Animal:
    def speak(self):
        raise NotImplementedError

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

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

2. 魔术方法

python 复制代码
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

三、异常处理进阶

python 复制代码
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"错误: {e}")
    # 记录日志后重新抛出
    raise  
else:
    print("无异常时执行")
finally:
    print("始终执行")

四、常用内置模块

1. collections模块

python 复制代码
from collections import defaultdict, Counter

# 自动初始化字典
dd = defaultdict(list)
dd['key'].append(1)

# 计数器
cnt = Counter('abracadabra')
print(cnt.most_common(2))  # [('a',5), ('b',2)]

2. itertools模块

python 复制代码
import itertools

# 组合迭代器
for pair in itertools.combinations('ABCD', 2):
    print(pair)  # ('A','B'), ('A','C')...

五、代码规范与优化

1. PEP8规范要点

  • 缩进:4空格
  • 行长度:不超过79字符
  • 导入:分模块导入,避免from module import *
  • 命名规范:类用CamelCase,变量用snake_case

2. 性能优化技巧

python 复制代码
# 使用join代替字符串拼接
result = ''.join([str(i) for i in range(100)])

# 局部变量访问更快
def calculate():
    local_sqrt = math.sqrt  # 缓存方法
    return local_sqrt(100)

六、实战练习

1. 数据清洗任务

python 复制代码
# 处理CSV文件,过滤无效数据
import csv

with open('data.csv') as f:
    reader = csv.DictReader(f)
    clean_data = [
        row for row in reader 
        if float(row['price']) > 0 
        and row['name'].strip() != ''
    ]

2. 简易网页爬虫

python 复制代码
import requests
from bs4 import BeautifulSoup

response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
titles = [h1.text for h1 in soup.find_all('h1')]

通过以上内容的学习,你将能够:

  1. 编写更Pythonic的代码
  2. 处理复杂程序结构
  3. 提升代码性能和可维护性
  4. 应对实际开发中的常见场景

建议配合实际项目练习,并阅读Python官方文档加深理解。

相关推荐
雨夜的星光1 小时前
Python JSON处理:load/loads/dump/dumps全解析
开发语言·python·json
fen_fen2 小时前
Java打包时,不将本地Jar打包到项目的最终 JAR 中
开发语言·python·pycharm
可触的未来,发芽的智生4 小时前
触摸未来2025.10.10:记忆的种子,当神经网络拥有了临时工作区,小名喜忆记系统
人工智能·python·神经网络·机器学习·架构
mortimer5 小时前
在 Windows 上部署 NVIDIA Parakeet-TDT 遇到的坑
python·github·nvidia
Rock_yzh5 小时前
AI学习日记——卷积神经网络(CNN):完整实现与可视化分析
人工智能·python·深度学习·神经网络·学习·cnn
生信小白菜儿5 小时前
深度学习(DL)概念及实例操作
人工智能·python·深度学习
测试老哥5 小时前
如何编写好测试用例?
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
郝学胜-神的一滴6 小时前
Effective Python 第44条:用纯属性与修饰器取代旧式的 setter 与 getter 方法
开发语言·python·程序人生·软件工程
嫂子的姐夫7 小时前
11-py调用js
javascript·爬虫·python·网络爬虫·爬山算法
图亚Vanta8 小时前
Python入门第一课:Python安装、VSCode/Pycharm配置
vscode·python·pycharm