编写一个动物类 Animal ,具有属性:名称和重量;具有功能:吃、睡。子类 Bird 和 Dog 继承了父类 Animal ,具有自己的属性,如翅膀和四肢等,同时改写父类的方法。使用 main 方法去测试所编写的类。
时间: 2023-04-09 17:04:33 浏览: 154
好的,我可以回答这个问题。以下是动物类 Animal 的代码:
```python
class Animal:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def eat(self):
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
```
接下来是子类 Bird 和 Dog 的代码:
```python
class Bird(Animal):
def __init__(self, name, weight, wings):
super().__init__(name, weight)
self.wings = wings
def fly(self):
print(f"{self.name} is flying with {self.wings} wings.")
def sleep(self):
print(f"{self.name} is sleeping on a branch.")
class Dog(Animal):
def __init__(self, name, weight, legs):
super().__init__(name, weight)
self.legs = legs
def bark(self):
print(f"{self.name} is barking with {self.legs} legs.")
def sleep(self):
print(f"{self.name} is sleeping in a doghouse.")
```
最后是 main 方法的代码:
```python
if __name__ == '__main__':
bird = Bird("Sparrow", 0.1, 2)
bird.eat()
bird.sleep()
bird.fly()
dog = Dog("Golden Retriever", 30, 4)
dog.eat()
dog.sleep()
dog.bark()
```
这个程序将输出以下内容:
```
Sparrow is eating.
Sparrow is sleeping on a branch.
Sparrow is flying with 2 wings.
Golden Retriever is eating.
Golden Retriever is sleeping in a doghouse.
Golden Retriever is barking with 4 legs.
```
希望这个回答能够帮助到您!