请尝试实现Beverage、Tea、Coffee、Beer类并给出简单的测试
时间: 2023-09-19 16:06:13 浏览: 99
Beverage类:
```
class Beverage:
def __init__(self, name, price):
self.name = name
self.price = price
def get_name(self):
return self.name
def get_price(self):
return self.price
def __str__(self):
return f"{self.name} - ${self.price:.2f}"
```
Tea类:
```
class Tea(Beverage):
def __init__(self, name, price, type):
super().__init__(name, price)
self.type = type
def get_type(self):
return self.type
def __str__(self):
return f"{self.name} - {self.type} - ${self.price:.2f}"
```
Coffee类:
```
class Coffee(Beverage):
def __init__(self, name, price, size):
super().__init__(name, price)
self.size = size
def get_size(self):
return self.size
def __str__(self):
return f"{self.name} - {self.size} - ${self.price:.2f}"
```
Beer类:
```
class Beer(Beverage):
def __init__(self, name, price, alcohol_content):
super().__init__(name, price)
self.alcohol_content = alcohol_content
def get_alcohol_content(self):
return self.alcohol_content
def __str__(self):
return f"{self.name} - {self.alcohol_content}% - ${self.price:.2f}"
```
测试:
```
tea = Tea("Green Tea", 3.5, "Loose Leaf")
print(tea.get_name()) # Green Tea
print(tea.get_type()) # Loose Leaf
print(tea.get_price()) # 3.5
print(tea) # Green Tea - Loose Leaf - $3.50
coffee = Coffee("Latte", 4.2, "Medium")
print(coffee.get_name()) # Latte
print(coffee.get_size()) # Medium
print(coffee.get_price()) # 4.2
print(coffee) # Latte - Medium - $4.20
beer = Beer("IPA", 5.8, 6.5)
print(beer.get_name()) # IPA
print(beer.get_alcohol_content()) # 6.5
print(beer.get_price()) # 5.8
print(beer) # IPA - 6.5% - $5.80
```
阅读全文