python super
时间: 2023-10-13 07:24:22 浏览: 34
在 Python 中,`super()` 函数是用于调用父类(超类)的一个方法。它通常用在子类的方法中,以便在子类中可以访问父类中的属性和方法。
使用 `super()` 函数有两种方式:
1. 调用父类的构造方法,可以使用 `super().__init__()` 语句。
```python
class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
```
在上面的例子中,`Child` 类继承了 `Parent` 类,并通过 `super().__init__(name)` 调用了 `Parent` 类的构造方法来初始化 `name` 属性。
2. 调用父类的方法,可以使用 `super().method()` 语句。
```python
class Parent:
def say_hello(self):
print("Hello from Parent")
class Child(Parent):
def say_hello(self):
super().say_hello()
print("Hello from Child")
```
在上面的例子中,`Child` 类覆盖了 `Parent` 类的 `say_hello()` 方法,并通过 `super().say_hello()` 调用了 `Parent` 类的 `say_hello()` 方法。这样就可以在子类中添加一些额外的逻辑,而不破坏父类原有的逻辑。
总之,使用 `super()` 函数可以更方便地管理继承关系并避免代码重复。