Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python @dataclass

作者:青灯寂焚   发布日期:2025-11-14   浏览:100

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

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站