父类引用指向子类对象python
时间: 2023-07-02 13:16:06 浏览: 194
在 Python 中,父类引用可以指向子类对象,这就是所谓的多态。例如,如果有一个 Animal 类和一个 Dog 类,Dog 类是 Animal 类的子类,那么可以这样定义一个 Animal 类型的变量 a,然后将它指向一个 Dog 类型的对象:
```
class Animal:
def speak(self):
print("动物叫声")
class Dog(Animal):
def speak(self):
print("汪汪汪")
a = Animal()
a.speak() # 输出 "动物叫声"
d = Dog()
d.speak() # 输出 "汪汪汪"
a = d
a.speak() # 输出 "汪汪汪"
```
在上面的代码中,a 最初指向一个 Animal 类型的对象,但是之后又将它指向了一个 Dog 类型的对象,这是完全合法的。调用 a 的 speak() 方法时,由于 a 现在指向的是一个 Dog 类型的对象,因此会输出 "汪汪汪"。这就是多态的体现。
相关问题
请按照以下要求设计一个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类重写了该方法,所以会输出“旺旺”这个字符串。
实现一个子类覆盖父类的方法startup,声明一个指向子类对象,类型为父类对象v,并调用方法startup
假设有一个父类`Parent`和一个子类`Child`,代码如下:
```python
class Parent:
def startup(self):
print("Parent startup...")
class Child(Parent):
def startup(self):
print("Child startup...")
```
我们可以创建一个指向子类对象、类型为父类对象的变量`v`:
```python
v = Child()
```
然后调用`v`的`startup`方法:
```python
v.startup()
```
由于`Child`类继承了`Parent`类并重写了`startup`方法,所以输出的结果应该是"Child startup..."。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)