实验要求:假设水果店所有的水果都是Fruit类,比如这些水果有苹果、桔子、香蕉。。。现在抽象出水果需要先购买后品尝。顾客类是Customer。
时间: 2024-05-14 18:19:26 浏览: 93
8类水果图片数据集(每类100张图片左右)['橘子','菠萝','苹果','木瓜','火龙果','香蕉','樱桃','芒果']
5星 · 资源好评率100%
好的,那我们可以先定义一个Fruit类,它包含水果的名称和价格属性,并且可以被购买和品尝。代码如下:
```python
class Fruit:
def __init__(self, name, price):
self.name = name
self.price = price
def buy(self):
print(f"You have bought {self.name} for {self.price} dollars.")
def taste(self):
print(f"You are tasting {self.name}.")
```
然后我们定义一个Customer类,它可以购买水果和品尝水果。代码如下:
```python
class Customer:
def __init__(self, name):
self.name = name
def buy_fruit(self, fruit):
fruit.buy()
def taste_fruit(self, fruit):
fruit.taste()
```
现在我们可以创建一些水果实例和顾客实例来测试我们的代码:
```python
apple = Fruit("apple", 2)
orange = Fruit("orange", 1.5)
banana = Fruit("banana", 0.5)
alice = Customer("Alice")
bob = Customer("Bob")
alice.buy_fruit(apple)
bob.buy_fruit(orange)
alice.taste_fruit(apple)
bob.taste_fruit(orange)
```
输出结果如下:
```
You have bought apple for 2 dollars.
You have bought orange for 1.5 dollars.
You are tasting apple.
You are tasting orange.
```
阅读全文