Python数据类实战:5个高效数据建模技巧
1. 基础数据类
创建简单的用户数据模型:
from dataclasses import dataclass
from typing import List
@dataclass
class User:
name: str
age: int
email: str = "" # 默认值
friends: List[str] = None # 可变默认值需要特殊处理
def __post_init__(self):
if self.friends is None:
self.friends = []
# 使用
user = User(name="张三", age=30, email="zhangsan@example.com")
print(user) # 自动生成__repr__
2. 不可变数据类
创建不可变的数据对象:
@dataclass(frozen=True)
class Point:
x: float
y: float
def distance(self, other):
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
# 使用
p1 = Point(1.0, 2.0)
p2 = Point(4.0, 6.0)
print(p1.distance(p2)) # 5.0
# p1.x = 3.0 # 报错: frozen实例不可修改
3. 数据类继承
实现数据类的继承关系:
@dataclass
class Product:
id: int
name: str
price: float
@dataclass
class DiscountedProduct(Product):
discount_rate: float = 0.1
@property
def discounted_price(self):
return self.price * (1 - self.discount_rate)
# 使用
product = DiscountedProduct(id=1, name="Python书", price=99.0, discount_rate=0.2)
print(f"折后价: {product.discounted_price}")
4. 数据类与模式匹配
Python 3.10+的结构模式匹配:
@dataclass
class Command:
action: str
data: str
def handle_command(cmd: Command):
match cmd:
case Command(action="create", data=data):
print(f"创建资源: {data}")
case Command(action="delete", data=data):
print(f"删除资源: {data}")
case _:
print("未知命令")
# 使用
handle_command(Command("create", "user"))
特性 | 普通类 | 数据类 |
---|---|---|
代码量 | 多 | 少 |
__init__ | 手动 | 自动 |
比较方法 | 手动 | 自动 |
5. 数据类转换
与JSON等格式互转:
from dataclasses import asdict, astuple
import json
@dataclass
class Book:
title: str
author: str
year: int
book = Book("Python编程", "Guido", 2023)
# 转为字典
book_dict = asdict(book)
print(json.dumps(book_dict))
# 转为元组
print(astuple(book))
# 从字典创建
data = {"title": "机器学习", "author": "Andrew", "year": 2022}
book2 = Book(**data)
Python数据类(dataclass)为数据建模提供了简洁高效的解决方案,特别适合DTO、配置对象等需要清晰数据结构定义的场景。