super 是干嘛用的?在 Python2 和 Python3 使用,有什么区别?为什么要使用 super?请举例说明
时间: 2024-05-03 22:18:46 浏览: 14
`super()` 是 Python 中用于调用父类方法的函数,它在 Python2 和 Python3 中的使用方式略有不同。
在 Python2 中,`super()` 函数需要传递两个参数,第一个参数是当前类的名字,第二个参数是类的实例。例如:
```python
class A(object):
def foo(self):
print('A.foo')
class B(A):
def foo(self):
print('B.foo')
super(B, self).foo()
b = B()
b.foo() # 输出 B.foo\nA.foo
```
在 Python3 中,`super()` 函数不需要传递任何参数,它会自动获取当前类和类的实例。例如:
```python
class A:
def foo(self):
print('A.foo')
class B(A):
def foo(self):
print('B.foo')
super().foo()
b = B()
b.foo() # 输出 B.foo\nA.foo
```
使用 `super()` 的好处是可以在子类中调用父类中的同名方法,并且不需要硬编码父类的名字。这样子类就可以灵活地继承和扩展父类的功能。
举个例子,假设有一个基类 `Animal`,它有一个 `speak()` 方法,子类 `Dog` 和 `Cat` 分别继承了 `Animal`,并且需要重写 `speak()` 方法:
```python
class Animal:
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return 'Woof!'
class Cat(Animal):
def speak(self):
return 'Meow!'
```
现在我们想让 `Dog` 和 `Cat` 能够发出声音并且能够同时输出基类 `Animal` 的信息,可以这样做:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return 'Animal speaks'
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
def speak(self):
return super().speak() + '\nWoof!'
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
def speak(self):
return super().speak() + '\nMeow!'
dog = Dog('Fido')
print(dog.speak()) # 输出 "Animal speaks\nWoof!"
cat = Cat('Fluffy')
print(cat.speak()) # 输出 "Animal speaks\nMeow!"
```
在上面的例子中,我们使用 `super()` 来调用基类 `Animal` 中的 `speak()` 方法,并且在子类的 `speak()` 方法中添加了自己的声音。这样就实现了子类对基类方法的重写,并且能够同时输出基类的信息。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)