dataclass_example.py
· 238 B · Python
Ham
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
email: str
# 建立實例
user = User(name="Tim", age=30, email="tim@example.com")
print(user) # User(name='Tim', age=30, email='tim@example.com')
| 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') |
| 12 |
dataclass_with_default.py
· 269 B · Python
Ham
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
stock: int = field(default=10) # 預設庫存為 10
product = Product(name="Laptop", price=999.99)
print(product) # Product(name='Laptop', price=999.99, stock=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) |
| 11 |
employee_with_post_init.py
· 370 B · Python
Ham
from dataclasses import dataclass, field
@dataclass
class Employee:
name: str
salary: float
department: str = "General"
def __post_init__(self):
self.salary = round(self.salary, 2) # 四捨五入薪資
employee = Employee(name="Alice", salary=1234.5678)
print(employee) # Employee(name='Alice', salary=1234.57, department='General')
| 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') |
| 14 |
shopping_cart_example.py
· 265 B · Python
Ham
from dataclasses import dataclass, field
from typing import List
@dataclass
class ShoppingCart:
items: List[str] = field(default_factory=list) # 預設為空列表
cart = ShoppingCart()
cart.items.append("Apple")
print(cart) # ShoppingCart(items=['Apple'])
| 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']) |
| 11 |