A. 数据结构
# 列表
list = [1, 'b', 2.71]
list.append("New")
print(list)
print(list[1:])
# 元组
tuple = (1, 'b', 2.71)
print(tuple[2])
T = tuple * 2
print(T)
# 字典
d = {2 : 1, 'w' : 'z'}
print(d[2])
B. 装饰器
本质上是一个接受函数作为参数并返回一个新函数的函数
通常用于日志记录、性能测试、事务处理、权限校验等场景
可以在不修改原始函数代码的情况下,增加额外的功能
在 Python 中,函数是一等公民,意味着函数可以像其他对象一样赋值给变量、作为参数传递和作为返回值
基本结构
def decorator(func):
def wrapper(*args, **kwargs):
# 在函数执行前可以添加一些代码
result = func(*args, **kwargs)
# 在函数执行后可以添加一些代码
return result
return wrapper
@decorator
def function_to_decorate():
pass
无参装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
有参装饰器
def my_decorator_with_args(decorator_arg1, decorator_arg2):
def decorator(func):
def wrapper(*args, **kwargs):
print("Decorator arguments:", decorator_arg1, decorator_arg2)
print("Something is happening before the function is called.")
func(*args, **kwargs)
print("Something is happening after the function is called.")
return wrapper
return decorator
@my_decorator_with_args("hello", "world")
def say_hello():
print("Hello!")
say_hello()
装饰器能够保留函数原信息
保留原函数的名称、文档字符串、参数列表
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello():
"""says hello"""
print("Hello!")
print(say_hello.__name__) # 输出: say_hello
装饰器用途 - 访问控制
from functools import wraps
from flask import session, redirect
def login_required(func):
@wraps(func)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return redirect('/login')
return func(*args, **kwargs)
return decorated_function
@app.route('/dashboard')
@login_required
def dashboard():
return 'Dashboard Page'
装饰器用途 - 输入验证
def validate_input(func):
@wraps(func)
def decorated_function(*args, **kwargs):
if not isinstance(kwargs['input'], int):
raise ValueError("Input must be an integer")
return func(*args, **kwargs)
return decorated_function
@validate_input
def process_input(input):
return input * 2
装饰器用途 - 日志记录
import logging
logging.basicConfig(level=logging.INFO)
def log_function(func):
@wraps(func)
def decorated_function(*args, **kwargs):
result = func(*args, **kwargs)
logging.info(f"{func.__name__} called with args={args}, kwargs={kwargs}, returned {result}")
return result
return decorated_function
@log_function
def add(a, b):
return a + b
装饰器用途 - 性能测试
import time
def performance_test(func):
@wraps(func)
def decorated_function(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time} seconds to run.")
return result
return decorated_function
@performance_test
def slow_function():
time.sleep(2)
return "Done"
装饰器用途 - 事务处理
from contextlib import contextmanager
import psycopg2
from functools import wraps
@contextmanager
def transaction(conn):
cursor = conn.cursor() # 创建游标对象
try:
yield cursor # yield返回游标,暂停执行,等待with块中的代码执行
conn.commit() # with块中的代码执行成功,提交事务
except:
conn.rollback() # 如果发生异常,回滚事务
raise # 重新抛出异常
finally:
cursor.close() # 无论成功还是失败,都关闭游标
def db_operation(func):
@wraps(func)
def decorated_function(*args, **kwargs):
with transaction(get_database_connection()) as cursor: # 使用with语句管理事务
return func(cursor, *args, **kwargs) # 调用原始函数,传入游标和其它参数
return decorated_function
@db_operation
def update_user_balance(cursor, user_id, amount):
cursor.execute("UPDATE users SET balance = balance + %s WHERE id = %s", (amount, user_id))
补充讲解:
在Web应用或API开发中,经常需要执行多个数据库操作来完成任务。使用事务可以确保这些操作要么全部成功,要么全部失败,避免数据不一致的问题。例如,在转账操作中,需要从一个账户扣款并给另一个账户加款,这两个操作必须在同一个事务中执行,以确保资金不会丢失或重复
通过这种方式,可以简化数据库操作代码,同时确保数据的一致性和完整性
数据库事务的基本概念:
数据库事务是指一系列操作组成的工作单元,这些操作要么全部成功,要么全部失败
ACID 特性:
- 原子性(Atomicity):事务中的所有操作要么全部完成,要么全部不完成,不会结束在中间某个环节
- 一致性(Consistency):事务必须使数据库从一个一致性状态变换到另一个一致性状态
- 隔离性(Isolation):一个事务的执行不能被其他事务干扰
- 持久性(Durability):一旦事务提交,则其所做的更改将永久保存在数据库中
提交事务使用commit()
方法,回滚事务使用rollback()
方法
C. 构造器和迭代器
构造器是一种特殊的方法,用于在创建对象时初始化对象。在Python中,构造器方法名为__init__
假设我们正在开发一个电商系统,需要创建一个Product
类来表示商品。每个商品都有名称、价格和库存量等属性
class Product:
def __init__(self, name, price, stock):
self.name = name # 商品名称
self.price = price # 商品价格
self.stock = stock # 商品库存
def __str__(self):
return f"Product({self.name}, Price: {self.price}, Stock: {self.stock})"
# 创建商品实例
product1 = Product("Laptop", 1000, 10)
print(product1)
迭代器是用于遍历序列(如列表、元组)的对象。迭代器实现了两个方法:__iter__()
和__next__()
在电商系统中,我们可能需要一个Inventory
类来管理多个商品。我们可以使Inventory
类成为一个迭代器,以便轻松遍历库存中的所有商品
class Inventory:
def __init__(self, products):
self.products = products # 商品列表
self.index = 0 # 当前遍历的位置
def __iter__(self):
return self # 返回迭代器对象本身
def __next__(self):
if self.index < len(self.products):
product = self.products[self.index]
self.index += 1
return product
else:
raise StopIteration # 遍历完成时抛出异常
# 创建商品列表
products = [Product("Laptop", 1000, 10), Product("Phone", 500, 20)]
# 创建库存实例
inventory = Inventory(products)
# 遍历库存中的所有商品
for product in inventory:
print(product)
D. 深拷贝和浅拷贝
浅拷贝(Shallow Copy)
浅拷贝创建一个新的复合对象,然后(在可能的情况下)将原对象中找到的引用插入到这个新对象中
实现方式:
copy.copy()
- 列表的切片操作
list[:]
- 列表的
list.copy()
- 字典的
dict.copy()
import copy
list1 = [1, 2, [3, 4]]
list2 = copy.copy(list1)
list2[2][0] = 999 # 修改子列表中的元素
print(list1) # 输出: [1, 2, [999, 4]],说明原列表也被修改了
场景示例:
在电商系统中,假设有一个商品列表,每个商品是一个包含名称和价格的字典
如果只是想复制这个列表用于展示,而不修改商品信息,可以使用浅拷贝
深拷贝(Deep Copy)
深拷贝创建一个新的复合对象,然后递归地复制原对象中找到的所有对象
实现方式:
copy.deepcopy()
import copy
list1 = [1, 2, [3, 4]]
list3 = copy.deepcopy(list1)
list3[2][0] = 999 # 修改子列表中的元素
print(list1) # 输出: [1, 2, [3, 4]],原列表保持不变
场景示例:
在电商系统中,如果需要复制一个商品列表并进行一些修改(如调整价格),以进行模拟或分析,而不希望影响原始数据,应使用深拷贝
# 假设促销活动A和B只是展示商品,不修改价格
products = [{'name': 'Laptop', 'price': 1000}, {'name': 'Phone', 'price': 500}]
promotion_a = copy.copy(products)
promotion_b = copy.copy(products) # 这里使用浅拷贝是安全的
# 模拟促销活动C,对商品进行打折
promotion_c = copy.deepcopy(products) # 这里使用深拷贝
for product in promotion_c:
product['price'] *= 0.9 # 打9折
# 原始商品列表保持不变
print(products) # 输出: [{'name': 'Laptop', 'price': 1000}, {'name': 'Phone', 'price': 500}]
E. 生成器
生成器(Generator)是Python中一种特殊的迭代器,它允许按需生成值,而不是一次性生成并存储所有值。这种“惰性计算”的方式在处理大量数据时可以节省内存
def simple_generator():
yield 1
yield 2
yield 3
gen = simple_generator()
for value in gen:
print(value)
# 生成器函数与普通函数类似,但使用yield语句而不是return语句。当函数执行到yield时,会返回一个值并暂停执行,直到下一次调用
gen_expr = (x * 2 for x in range(1, 4))
for value in gen_expr:
print(value)
# 生成器表达式与列表推导式类似,但使用圆括号而不是方括号
工作原理:
生成器在执行时,会保存其函数的状态,包括局部变量和指令指针。当调用next()
函数或使用for循环遍历生成器时,生成器会从上次暂停的地方继续执行,直到遇到下一个yield
语句或函数结束
具体示例:
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib_gen = fibonacci_generator()
for _ in range(10):
print(next(fib_gen))
# 斐波那契数列生成器
def file_reader(file_name):
with open(file_name, 'r') as file:
for line in file:
yield line.strip()
for line in file_reader('example.txt'):
print(line)
# 文件读取生成器
F. 序列器和反序列器
序列器用于将数据结构(如字典、列表、对象等)或对象状态转换为一种可以存储或传输的格式,如JSON、XML等。这种转换使得数据可以在不同的系统或程序之间进行交换
# json库
import json
data = {'name': 'Alice', 'age': 25}
json_string = json.dumps(data)
print(json_string) # 输出:{"name": "Alice", "age": 25}
with open('data.json', 'w') as f:
json.dump(data, f)
# # # # # # # # # # # # # # # # # # # # # #
import json
json_string = '{"name": "Alice", "age": 25}'
data = json.loads(json_string)
print(data) # 输出:{'name': 'Alice', 'age': 25}
with open('data.json', 'r') as f:
data = json.load(f)