from dataclasses import dataclass
@dataclass
class InventoryItem:
"""A class representing an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
"""Calculate the total cost of the inventory item."""
return self.unit_price * self.quantity_on_hand
# Example usage:
item = InventoryItem(name="Widget", unit_price=10.0, quantity_on_hand=5)
print(f"Item: {item.name}, Total Cost: ${item.total_cost()}")
@dataclass 是 Python 的一个装饰器,用于自动生成特殊方法(如 __init__, __repr__, __eq__ 等)。InventoryItem 类使用了 @dataclass 装饰器,因此它会自动获得一个构造函数 (__init__) 和其他有用的方法。name, unit_price, 和 quantity_on_hand 是类的属性。其中 quantity_on_hand 有一个默认值 0。total_cost 方法计算库存物品的总成本,即单价乘以数量。InventoryItem 实例并打印其名称和总成本。Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站