这是我一直在编写的代码:
定义车辆类别
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/