python中super().
时间: 2024-03-20 08:36:11 浏览: 26
在Python中,super()是一个内置函数,用于调用父类的方法。它可以在子类中调用父类的方法,以便在子类中扩展或重写父类的功能。
super()函数的常见用法是在子类的构造函数中调用父类的构造函数。通过使用super()函数,子类可以继承并执行父类的构造函数中的代码,从而确保父类的初始化工作得以完成。
以下是super()函数的一些常见用法:
1. 在子类的构造函数中调用父类的构造函数:
```python
class ChildClass(ParentClass):
def __init__(self, arg1, arg2):
super().__init__(arg1) # 调用父类的构造函数
self.arg2 = arg2
```
2. 在子类中调用父类的方法:
```python
class ChildClass(ParentClass):
def some_method(self):
super().some_method() # 调用父类的方法
# 执行子类特有的代码
```
3. 在多重继承中使用super()函数:
```python
class ChildClass(ParentClass1, ParentClass2):
def some_method(self):
super(ParentClass1, self).some_method() # 调用指定父类的方法
# 执行子类特有的代码
```
需要注意的是,super()函数只能在新式类(继承自object)中使用,而在旧式类中无法使用。