Naposledy aktivní 9 months ago

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

timmy revidoval tento gist 9 months ago. Přejít na revizi

4 files changed, 44 insertions

dataclass_example.py(vytvořil soubor)

@@ -0,0 +1,11 @@
1 + from dataclasses import dataclass
2 +
3 + @dataclass
4 + class User:
5 + name: str
6 + age: int
7 + email: str
8 +
9 + # 建立實例
10 + user = User(name="Tim", age=30, email="tim@example.com")
11 + print(user) # User(name='Tim', age=30, email='tim@example.com')

dataclass_with_default.py(vytvořil soubor)

@@ -0,0 +1,10 @@
1 + from dataclasses import dataclass, field
2 +
3 + @dataclass
4 + class Product:
5 + name: str
6 + price: float
7 + stock: int = field(default=10) # 預設庫存為 10
8 +
9 + product = Product(name="Laptop", price=999.99)
10 + print(product) # Product(name='Laptop', price=999.99, stock=10)

employee_with_post_init.py(vytvořil soubor)

@@ -0,0 +1,13 @@
1 + from dataclasses import dataclass, field
2 +
3 + @dataclass
4 + class 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 +
12 + employee = Employee(name="Alice", salary=1234.5678)
13 + print(employee) # Employee(name='Alice', salary=1234.57, department='General')

shopping_cart_example.py(vytvořil soubor)

@@ -0,0 +1,10 @@
1 + from dataclasses import dataclass, field
2 + from typing import List
3 +
4 + @dataclass
5 + class ShoppingCart:
6 + items: List[str] = field(default_factory=list) # 預設為空列表
7 +
8 + cart = ShoppingCart()
9 + cart.items.append("Apple")
10 + print(cart) # ShoppingCart(items=['Apple'])
Novější Starší