python的super()如何使用
时间: 2024-06-14 08:05:05 浏览: 13
Python的super()函数用于在子类中调用父类的方法。它的使用方式为`super().父类方法()`。下面是一个示例:
```python
class Parent:
def __init__(self):
self.parent_attr = "Parent attribute"
def parent_method(self):
print("This is the parent method")
class Child(Parent):
def __init__(self):
super().__init__() # 调用父类的构造方法
self.child_attr = "Child attribute"
def child_method(self):
super().parent_method() # 调用父类的方法
print("This is the child method")
child = Child()
child.child_method()
```
输出结果为:
```
This is the parent method
This is the child method
```
在上面的示例中,子类`Child`继承了父类`Parent`。在子类的构造方法中,使用`super().__init__()`调用了父类的构造方法,以初始化父类的属性。在子类的方法`child_method()`中,使用`super().parent_method()`调用了父类的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)