Utoljára aktív 9 months ago

dataclass 提供簡潔的方式來定義類別,適用於需要 存儲資料、簡化初始化、提升可讀性 的場景,例如 設定管理、數據建模、API 資料結構。

Revízió af3ae586556212a36c8edfaafd053dfe4d2148a5

dataclass_example.py Eredeti
1from dataclasses import dataclass
2
3@dataclass
4class User:
5 name: str
6 age: int
7 email: str
8
9# 建立實例
10user = User(name="Tim", age=30, email="tim@example.com")
11print(user) # User(name='Tim', age=30, email='tim@example.com')
12
dataclass_with_default.py Eredeti
1from dataclasses import dataclass, field
2
3@dataclass
4class Product:
5 name: str
6 price: float
7 stock: int = field(default=10) # 預設庫存為 10
8
9product = Product(name="Laptop", price=999.99)
10print(product) # Product(name='Laptop', price=999.99, stock=10)
11
employee_with_post_init.py Eredeti
1from dataclasses import dataclass, field
2
3@dataclass
4class Employee:
5 name: str
6 salary: float
7 department: str = "General"
8
9 def __post_init__(self):
10 self.salary = round(self.salary, 2) # 四捨五入薪資
11
12employee = Employee(name="Alice", salary=1234.5678)
13print(employee) # Employee(name='Alice', salary=1234.57, department='General')
14
shopping_cart_example.py Eredeti
1from dataclasses import dataclass, field
2from typing import List
3
4@dataclass
5class ShoppingCart:
6 items: List[str] = field(default_factory=list) # 預設為空列表
7
8cart = ShoppingCart()
9cart.items.append("Apple")
10print(cart) # ShoppingCart(items=['Apple'])
11