温馨提示×

python调用父类的方法是什么

小亿
73
2023-11-01 09:23:23
栏目: 编程语言

在Python中,要调用父类的方法,可以使用`super()`函数来实现。
在子类中,通过`super()`函数可以调用父类的方法,从而实现对父类方法的重用。
`super()`函数需要传递两个参数:子类名和self对象。通过这两个参数,`super()`函数可以找到当前子类的父类,并调用父类中相应的方法。
以下是一个示例代码:
```python
class ParentClass:
   def __init__(self):
       self.name = "Parent"
   def say_hello(self):
       print("Hello from Parent")
class ChildClass(ParentClass):
   def __init__(self):
       super().__init__()  # 调用父类的构造方法
       self.name = "Child"
   def say_hello(self):
       super().say_hello()  # 调用父类的方法
       print("Hello from Child")
child = ChildClass()
child.say_hello()
```
输出结果为:

```
Hello from Parent
Hello from Child
```
在上述示例中,`ChildClass`继承自`ParentClass`,在子类的`__init__`方法中通过`super().__init__()`调用了父类的构造方法,并在子类的`say_hello`方法中通过`super().say_hello()`调用了父类的方法。

0