python中定义一个花的基类,包含2个属性和至少一个方法,再定义玫瑰花和月季花两个派生类,在派生类中,对基类的方法进行改写。最后分别创建3支玫瑰和5支月季花分别送给8个同学。
时间: 2023-06-06 18:06:12 浏览: 206
好的,这个问题属于技术问题,我可以为您解答。
下面是一种可能的实现方式:
```python
class Flower:
def __init__(self, name, color):
self.name = name
self.color = color
def get_description(self):
return f"This is a {self.color} {self.name}."
class Rose(Flower):
def get_description(self):
return f"This is a {self.color} rose, the symbol of love."
class Hydrangea(Flower):
def get_description(self):
return f"This is a {self.color} hydrangea, the flower of gratitude."
roses = [Rose('rose', 'red') for _ in range(3)]
hydrangeas = [Hydrangea('hydrangea', 'pink') for _ in range(5)]
for i, flower in enumerate(roses + hydrangeas):
print(f"Student {i+1} receives: {flower.get_description()}")
```
输出为:
```
Student 1 receives: This is a red rose, the symbol of love.
Student 2 receives: This is a red rose, the symbol of love.
Student 3 receives: This is a red rose, the symbol of love.
Student 4 receives: This is a pink hydrangea, the flower of gratitude.
Student 5 receives: This is a pink hydrangea, the flower of gratitude.
Student 6 receives: This is a pink hydrangea, the flower of gratitude.
Student 7 receives: This is a pink hydrangea, the flower of gratitude.
Student 8 receives: This is a pink hydrangea, the flower of gratitude.
```
希望能对您有所帮助!