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=3.5, quantity_on_hand=10)
print(item)
print(f"Total cost: {item.total_cost()}")
@dataclass 是 Python 的一个装饰器,用于自动生成特殊方法(如 __init__, __repr__, __eq__ 等)。InventoryItem 类使用了 @dataclass 装饰器,因此 Python 会自动为它生成构造函数 (__init__) 和其他常用方法。name, unit_price, 和 quantity_on_hand 是类的属性,其中 quantity_on_hand 有一个默认值 0。total_cost 方法计算库存项的总成本,即单价乘以数量。InventoryItem 实例并打印其信息和总成本。上一篇:python peewee
下一篇:python gunicorn
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站