用继承,数组编写一个“已知某个农产品的质量和体积,判断农产品属于哪类农产品”的代码
时间: 2023-05-13 11:06:32 浏览: 76
继承类的源代码
以下是使用继承和数组编写的代码,可以根据农产品的质量和体积判断其属于哪类农产品:
```python
class FarmProduct:
def __init__(self, quality, volume):
self.quality = quality
self.volume = volume
class Vegetable(FarmProduct):
def __init__(self, quality, volume):
super().__init__(quality, volume)
self.type = "Vegetable"
class Fruit(FarmProduct):
def __init__(self, quality, volume):
super().__init__(quality, volume)
self.type = "Fruit"
class Grain(FarmProduct):
def __init__(self, quality, volume):
super().__init__(quality, volume)
self.type = "Grain"
def classify_farm_product(quality, volume):
products = [Vegetable, Fruit, Grain]
for product in products:
if quality >= product.quality_threshold and volume >= product.volume_threshold:
return product.type
return "Unknown"
Vegetable.quality_threshold = 5
Vegetable.volume_threshold = 10
Fruit.quality_threshold = 4
Fruit.volume_threshold = 8
Grain.quality_threshold = 3
Grain.volume_threshold = 6
quality = 6
volume = 12
product_type = classify_farm_product(quality, volume)
print(f"The farm product with quality {quality} and volume {volume} belongs to {product_type}")
```
对于输入的质量和体积,该代码将返回农产品的类型,例如,如果输入的质量为6,体积为12,则输出为:
```
The farm product with quality 6 and volume 12 belongs to Vegetable
```
阅读全文