两者有什么区别举个例子
时间: 2023-10-15 22:08:14 浏览: 63
假设我们有一个父类和一个子类,它们的定义如下:
```
class Parent:
def __init__(self, arg1):
self.arg1 = arg1
def method1(self):
print("Parent's method1")
class Child(Parent):
def __init__(self, arg1, arg2):
super().__init__(arg1)
self.arg2 = arg2
def method1(self):
super().method1()
print("Child's method1")
```
在这个例子中,Parent类有一个构造函数__init__()和一个方法method1(),而Child类继承了Parent类,并且覆盖了method1()方法。在Child类的构造函数__init__()中,我们使用super()函数来调用Parent类的构造函数__init__(),并传递一个参数arg1。在Child类的method1()方法中,我们使用super()函数来调用Parent类的method1()方法,并在此基础上进行扩展。
现在假设我们创建一个Child类的实例并调用它的method1()方法:
```
child = Child("arg1", "arg2")
child.method1()
```
这将输出以下内容:
```
Parent's method1
Child's method1
```
这里我们可以看到,使用super()函数调用父类的方法时,可以保留父类的行为,并在此基础上进行扩展。在这个例子中,Child类的method1()方法调用了Parent类的method1()方法,而不是完全替换它。这种行为通常称为方法重写(override)和方法调用(call)。而如果没有使用super()函数,而是直接覆盖或替换了父类的方法,那么就会失去父类的行为。