用面向对象思想实现当铺典当功能,所有手表类商品当铺评定都是200元,所有服 装类商品当铺评定50元,所有电动车类商品当铺评定800元,根据所要典当的商品 使用统一方式输出要当商品的价格。
时间: 2024-05-10 12:18:28 浏览: 18
可以先定义一个父类 `Commodity` 表示所有商品的共性,然后再定义三个子类分别表示手表、服装和电动车。然后在每个子类中重写 `get_price()` 方法,来实现具体的价格评定。
代码示例:
```python
class Commodity:
def __init__(self, name):
self.name = name
def get_price(self):
pass
class Watch(Commodity):
def __init__(self, name):
super().__init__(name)
def get_price(self):
return 200
class Clothing(Commodity):
def __init__(self, name):
super().__init__(name)
def get_price(self):
return 50
class ElectricVehicle(Commodity):
def __init__(self, name):
super().__init__(name)
def get_price(self):
return 800
```
使用时,可以根据所要典当的商品创建相应的对象,并调用 `get_price()` 方法获取价格,例如:
```python
watch = Watch("劳力士手表")
price = watch.get_price()
print(f"{watch.name} 当铺评定价格为 {price} 元")
clothing = Clothing("卫衣")
price = clothing.get_price()
print(f"{clothing.name} 当铺评定价格为 {price} 元")
electric_vehicle = ElectricVehicle("特斯拉电动车")
price = electric_vehicle.get_price()
print(f"{electric_vehicle.name} 当铺评定价格为 {price} 元")
```