python里的super
时间: 2023-12-05 09:40:58 浏览: 22
在Python中,super()是一个内置函数,它返回一个临时对象,该对象允许您调用父类的方法。super()函数最常用的情况是在子类的__init__()方法中调用父类的__init__()方法。这样可以确保在子类中定义的任何新属性都会添加到子类中,而不是父类中。下面是一个例子:
```python
class A:
def __init__(self):
print('A.__init__')
class B(A):
def __init__(self):
super().__init__()
print('B.__init__')
b = B()
```
输出结果为:
```
A.__init__
B.__init__
```
在这个例子中,我们定义了两个类A和B,B是A的子类。在B的__init__()方法中,我们使用super()函数调用了A的__init__()方法,这样就可以确保A的__init__()方法被正确地调用。这是一种非常常见的用法,因为它允许您在子类中添加新的行为,而不会破坏父类的行为。
--相关问题--:
1. super()函数的作用是什么?
2. 如何在Python 2.x
相关问题
python里super的用法
在 Python 中,`super()` 是一个用于调用父类方法的内置函数。它常用于子类的初始化方法中,以确保子类能够继承父类的属性和方法。
使用 `super()` 的一般用法是在子类的初始化方法中调用父类的初始化方法,例如:
```python
class ChildClass(ParentClass):
def __init__(self, arg1, arg2):
super().__init__(arg1) # 调用父类的初始化方法
self.arg2 = arg2
```
在上述例子中,`ChildClass` 是一个继承自 `ParentClass` 的子类。子类的初始化方法中使用 `super().__init__(arg1)` 调用父类的初始化方法,并将 `arg1` 作为参数传递给父类的初始化方法。这样,子类既能够完成自己的初始化逻辑,又能够继承父类的属性和方法。
需要注意的是,`super()` 函数可以根据方法调用的上下文自动确定调用哪个父类的方法。此外,还可以传递额外的参数给 `super()`,以便在调用父类方法时传递给父类。
Python继承super
在 Python 中,继承是一种实现代码重用的方式,它允许你创建一个新类,该类具有现有类的属性和方法。在继承中,被继承的类称为父类或超类,继承的类称为子类。当子类继承了父类的属性和方法后,它可以通过重写父类的方法来实现自己特有的行为,也可以添加自己的属性和方法。而 super() 函数可以用来调用父类中的方法。
当子类继承了父类的方法后,如果在子类中需要使用父类中已经存在的方法,可以使用 super() 函数来调用父类中的方法。super() 函数返回一个代理对象,通过这个代理对象可以调用父类中的方法。使用 super() 函数的语法如下:
```python
class SubClass(ParentClass):
def some_method(self, arg):
super().some_method(arg) # 调用父类中的 some_method() 方法
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![](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)