实验 27 面向对象编程 、编程实现 1、用Animal类创建Mini对象和Polly对象,并调用类中的方法。(教材 P112 页例6.2)。 2、定义一个动物类Animal,然后定义Bird类和Cat类继承Animal类。(教材 P112 页例6.3) 3、定义一个宠物猫类继承动物类和宠物类。《教材P114页例6.4) 4、在动物类下面编写一个eat()方法,用一个函数调用不同实例地eatO方法。(教材P115页例6.5) 5、定义一个水果类,然后通过水果类创建苹果对象 橘子对象西瓜对象并分别添加颜色属性。(教材 P121 页思考题 3) 二、提交作业 (1)建立“实验27”文件来,把编程实现的1至5题放入该文件夹,下课前10分钟通过学生端发送给老师。
时间: 2024-02-20 21:57:06 浏览: 83
好的,我明白了你的问题。以下是回答:
1. Mini对象和Polly对象的创建及方法调用代码如下:
```python
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
pass
class Mini(Animal):
def sound(self):
print("Mini says meow!")
class Polly(Animal):
def sound(self):
print("Polly says squawk!")
mini = Mini("Mini")
polly = Polly("Polly")
mini.sound() # 输出:Mini says meow!
polly.sound() # 输出:Polly says squawk!
```
2. 定义动物类Animal、Bird类和Cat类继承Animal类的代码如下:
```python
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
pass
class Bird(Animal):
def sound(self):
print("Bird chirps!")
class Cat(Animal):
def sound(self):
print("Cat meows!")
bird = Bird("Bird")
cat = Cat("Cat")
bird.sound() # 输出:Bird chirps!
cat.sound() # 输出:Cat meows!
```
3. 定义宠物猫类继承动物类和宠物类的代码如下:
```python
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
pass
class Pet:
def __init__(self, name, owner):
self.name = name
self.owner = owner
class PetCat(Animal, Pet):
def sound(self):
print("Pet cat meows!")
cat = PetCat("Fluffy", "John")
cat.sound() # 输出:Pet cat meows!
print(cat.owner) # 输出:John
```
4. 在动物类下面编写一个eat()方法,用一个函数调用不同实例地eat()方法的代码如下:
```python
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
pass
def eat(self):
print(f"{self.name} is eating.")
class Bird(Animal):
def sound(self):
print("Bird chirps!")
class Cat(Animal):
def sound(self):
print("Cat meows!")
bird = Bird("Bird")
cat = Cat("Cat")
def feed(animal):
animal.eat()
feed(bird) # 输出:Bird is eating.
feed(cat) # 输出:Cat is eating.
```
5. 定义水果类,并通过水果类创建苹果对象、橘子对象、西瓜对象并分别添加颜色属性的代码如下:
```python
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
apple = Fruit("Apple", "Red")
orange = Fruit("Orange", "Orange")
watermelon = Fruit("Watermelon", "Green")
print(apple.color) # 输出:Red
print(orange.color) # 输出:Orange
print(watermelon.color) # 输出:Green
```
以上就是对你提出的问题的回答,希望能够帮助到你。
阅读全文