写一个小程序,实现面向对象编程的继承、封装和多态性的代码
时间: 2024-05-22 21:15:49 浏览: 56
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
pass
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self):
return "Woof!"
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
return "Meow!"
class Zoo:
def __init__(self):
self.animals = []
def add_animal(self, animal):
self.animals.append(animal)
def show_animals(self):
for animal in self.animals:
print(f"{animal.name} is {animal.age} years old and says {animal.speak()}")
dog1 = Dog("Fido", 3, "Golden Retriever")
cat1 = Cat("Fluffy", 2, "Gray")
zoo1 = Zoo()
zoo1.add_animal(dog1)
zoo1.add_animal(cat1)
zoo1.show_animals() # Output: Fido is 3 years old and says Woof!
# Fluffy is 2 years old and says Meow!
阅读全文