谈谈Python中的 super 举一个例子说明,再举一个科学计算的例子进一步说明
时间: 2024-02-18 15:06:24 浏览: 29
好的,下面我会分别举两个例子来说明 `super()` 函数的使用。
例子1:调用父类方法
假设我们有一个父类 `Person`,其中有一个方法 `walk()`,用来描述人的行走方式。我们再定义一个子类 `Student`,继承自 `Person`,并且重写了 `walk()` 方法,用来描述学生的行走方式。代码如下:
```python
class Person:
def walk(self):
print('Person is walking...')
class Student(Person):
def walk(self):
super().walk()
print('Student is walking...')
```
在上面的代码中,我们在子类 `Student` 的 `walk()` 方法中使用了 `super().walk()`,这样就可以先调用父类 `Person` 的 `walk()` 方法,然后再输出学生的行走方式。
当我们通过 `Student` 类创建一个对象,并调用 `walk()` 方法时,会输出以下结果:
```
Person is walking...
Student is walking...
```
可以看到,在 `Student` 类的 `walk()` 方法中,首先调用了父类 `Person` 的 `walk()` 方法,然后再输出了学生的行走方式。这样做的好处是,当我们修改父类 `Person` 的 `walk()` 方法时,子类 `Student` 的方法也会随之改变,而不需要手动修改子类的方法。
例子2:科学计算中的例子
在科学计算中,经常需要进行矩阵运算。假设我们有一个父类 `Matrix`,其中有一个方法 `dot()`,用来计算矩阵的乘积。我们再定义一个子类 `SquareMatrix`,继承自 `Matrix`,并且重写了 `dot()` 方法,用来计算方阵的乘积。代码如下:
```python
class Matrix:
def dot(self, other):
# 计算矩阵乘积的代码
pass
class SquareMatrix(Matrix):
def dot(self, other):
super().dot(other)
# 计算方阵乘积的代码
pass
```
在上面的代码中,我们在子类 `SquareMatrix` 的 `dot()` 方法中使用了 `super().dot(other)`,这样就可以先调用父类 `Matrix` 的 `dot()` 方法,然后再计算方阵的乘积。
当我们通过 `SquareMatrix` 类创建两个对象 `a` 和 `b`,并调用 `a.dot(b)` 方法时,会先调用父类 `Matrix` 的 `dot()` 方法,然后再计算方阵的乘积。这样做的好处是,当我们修改父类 `Matrix` 的 `dot()` 方法时,子类 `SquareMatrix` 的方法也会随之改变,而不需要手动修改子类的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)