基础知识
Python 核心概念
Python 是一种解释型、高级、通用的编程语言,以简洁易读的语法著称,广泛应用于 Web 开发、数据分析、人工智能等领域。
Python 语法
Python 使用缩进来表示代码块,语法简洁明了。支持多种编程范式,包括面向对象、函数式和过程式编程。
- 动态类型,无需声明变量类型
- 使用缩进表示代码块,强制代码规范
- 丰富的内置数据类型和函数
数据结构
Python 提供了多种内置数据结构:
- 列表(List):有序可变序列
- 元组(Tuple):有序不可变序列
- 字典(Dict):键值对映射
- 集合(Set):无序不重复元素集
函数
函数是 Python 中的一等公民,支持匿名函数(lambda)、高阶函数、闭包等特性。
面向对象
Python 支持面向对象编程,包括类、继承、多态、封装等特性。所有类都继承自 object。
GIL(全局解释器锁)
GIL 是 CPython 解释器的机制,确保同一时间只有一个线程执行 Python 字节码。这意味着多线程不能充分利用多核 CPU。
图文教程
步骤一:列表推导式
# 基本列表推导式
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
步骤二:字典操作
# 创建字典
user = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
# 访问和修改
print(user['name']) # Alice
user['age'] = 26
# 常用方法
user.get('email', 'N/A') # 安全获取,不存在返回默认值
user.keys() # dict_keys(['name', 'age', 'city'])
user.values() # dict_values(['Alice', 26, 'Beijing'])
user.items() # 返回键值对元组列表
# 合并字典
dict1 = {'a': 1}
dict2 = {'b': 2}
merged = {**dict1, **dict2} # {'a': 1, 'b': 2}
步骤三:类与对象、装饰器
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
# 装饰器
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time() - start:.2f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "Done"
代码实操
阅读以下代码,理解实现原理,然后尝试修改并运行
实践任务:装饰器实现缓存
def memoize(func):
"""缓存装饰器,缓存函数计算结果"""
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
wrapper.cache = cache
return wrapper
@memoize
def fibonacci(n):
"""计算斐波那契数列"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(30))
print(len(fibonacci.cache))
练习任务
- 为缓存装饰器添加缓存大小限制(LRU 策略)
- 支持关键字参数的缓存
- 添加缓存过期时间功能