python - 如何使用 __init__ 缩短这段代码?

标签 python python-3.x function class init

这是我一直在编写的代码:

定义车辆类别

class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def description(self):
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str
# your code goes here
car1 = Vehicle()
name = "Fer"
kind = "convertible"
color = "red"
value = 60,000.00
car2 = Vehicle()
name = "Jump"
kind = "van"
color = "blue"
value = 10,000.00
# test code
print(car1.description())
print(car2.description())

我想使用init缩短这个时间,但我还没有成功

最佳答案

如果 __init__ 方法像这样简单,你可以 dataclass .

直接回答你的问题,是这样的:

from dataclasses import dataclass

@dataclass
class Vehicle:
    name: str
    kind: str
    color: str
    value: float

    def description(self) -> str:
        return "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)

v1 = Vehicle("Fer", "convertible", "red", 60_000.0)
v2 = Vehicle("Jump", "van", "blue", 10_000.0)

但是您可以对此进行一些改进。

  • 车辆种类有限 目前,kind 可以是任何字符串,但大概车辆的种类数量有限,因此您可以限制为这些。我会使用Enum
  • 即使可能有默认值,您也必须指定所有内容
  • 描述可以是属性
  • 使用格式化字符串(新标准)

把它们放在一起看起来像这样:

from dataclasses import dataclass
from enum import Enum

class VehicleKind(Enum):
    CAR = "car"
    VAN = "van"
    CONVERTIBLE = "convertible"


@dataclass
class Vehicle:
    name: str
    color: str
    kind: VehicleKind = VehicleKind.CAR
    value: float = 100.0

    @property
    def description(self) -> str:
        return f"{self.name} is a {self.color} {self.kind.value} worth {self.value:.2f}"

v1 = Vehicle("Fer", "red", VehicleKind.CONVERTIBLE, 60_000.0)
v2 = Vehicle("Jump", "blue", VehicleKind.VAN, 10_000.0)

print(Vehicle("Default", "green").description)
# Default is a green car worth 100.00

关于python - 如何使用 __init__ 缩短这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73638192/

相关文章:

python - 导入 Turicreate 出现错误 No module named 'turicreate.cython.cy_unity'

c - 为什么 func 看起来和 C 中的 &func 一样?

javascript - 如何在 jQuery ajax 函数中使用 URL 变量?

python - 在导入中绕过 Python 导入的方法?

python - 创建 csv 文件并根据该列附加数据(如果文件名相同)

python - 仅分配一次值的 defaultdict 变体

python - 使用装饰器时无法获取方法名称

python - Django:如何迁移在运行时创建的动态模型

Python 解析时出现意外的 EOF

javascript - 为什么 Crockford 使用这种格式来编写 JSON.parse 函数?