1、定义一个类Animal,具有名称name,颜色color属性,模拟叫声shout0方法。 定义一子类Tiger,继承父类Animal,实现独有的特性feature,独有的shout“ 嗷鸣.嗷鸣…
时间: 2024-05-29 13:11:51 浏览: 14
class Animal:
def __init__(self, name, color):
self.name = name
self.color = color
def shout(self):
print("Animal is shouting")
class Tiger(Animal):
def __init__(self, name, color, feature):
super().__init__(name, color)
self.feature = feature
def shout(self):
print("嗷鸣.嗷鸣...")
tiger = Tiger("老虎", "黄色", "有黑色条纹")
print(tiger.name) # 老虎
print(tiger.color) # 黄色
print(tiger.feature) # 有黑色条纹
tiger.shout() # 嗷鸣.嗷鸣...
相关问题
父类Animal中声明Name属性、以及Shout方法代码
Animal类中声明Name属性和Shout方法的代码如下:
```
class Animal {
public:
string Name;
virtual void Shout() = ;
};
```
其中,Name属性是一个字符串类型的公共属性,表示动物的名称;Shout方法是一个纯虚函数,表示动物的叫声,由子类实现具体的叫声。
请按照以下要求设计一个Animal抽象类 (1)抽象类中有唯一的抽象方法shout()方法 (2)编写一个Dog类去继承Animal抽象类,并重写shout方法,方法体为输出结果为:旺旺(3)编写测试类,利用父类引用指向子类对象,调用shout方法
好的,根据您的要求,我为您设计Animal抽象类,并且编写Dog类去继承Animal抽象类并重写shout方法,以及编写一个测试类进行测试。
Animal抽象类设计如下:
```python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def shout(self):
pass
```
这里使用了Python的abc模块来定义抽象类Animal,其中定义了一个抽象方法shout(),这个方法在子类中必须被重写。
接下来,我们根据您的要求编写Dog类:
```python
class Dog(Animal):
def shout(self):
print("旺旺")
```
这里定义了Dog类继承了Animal抽象类,并且重写了shout()方法,当我们调用Dog类的shout()方法时,会输出“旺旺”这个字符串。
最后,我们编写一个测试类进行测试:
```python
class Test:
def test(self):
animal = Dog()
animal.shout()
test = Test()
test.test()
```
这里我们定义了一个Test类,其中有一个test()方法,该方法中使用Animal类的引用指向Dog类的实例对象,然后调用Animal类的shout()方法,由于Dog类重写了该方法,所以会输出“旺旺”这个字符串。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)