定义一个动物类,定义动物类的2个子类,定义一个测试类。要求动物类是抽象类。
时间: 2024-05-15 16:16:19 浏览: 91
AI动物识别图像分类数据集
```python
# 定义抽象类Animal
from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
@abstractmethod
def speak(self):
pass
# 定义子类Cat
class Cat(Animal):
def __init__(self, name, age, gender):
super().__init__(name, age, gender)
def speak(self):
print(f"{self.name} says meow")
# 定义子类Dog
class Dog(Animal):
def __init__(self, name, age, gender):
super().__init__(name, age, gender)
def speak(self):
print(f"{self.name} says bark")
# 测试类
if __name__ == "__main__":
cat = Cat("Tom", 3, "male")
cat.speak() # 输出:Tom says meow
dog = Dog("Jerry", 4, "female")
dog.speak() # 输出:Jerry says bark
```
阅读全文