调用父类函数时super()里面还写了self和子类函数是什么意思
时间: 2024-04-21 16:23:39 浏览: 13
调用父类函数时,`super()`函数用于调用父类的方法。在使用`super()`时,需要传递两个参数:子类的类名和子类的实例对象。其中,`self`表示子类的实例对象,而子类函数则表示当前正在执行的子类方法。
通过在子类中使用`super()`函数,可以在子类中调用父类的方法并执行父类中的逻辑。这在需要在子类中扩展或修改父类方法的情况下非常有用。
相关问题
子类方法中调用父类函数中self.变量是子类的还是父类的
在子类中调用父类的方法时,self指向的是子类的实例,所以self.变量会先在子类中查找,如果找不到则会到父类中查找。
例如:
```python
class Parent:
def __init__(self):
self.x = 1
def print_x(self):
print(self.x)
class Child(Parent):
def __init__(self):
super().__init__()
self.x = 2
parent = Parent()
child = Child()
parent.print_x() # 输出 1
child.print_x() # 输出 2
```
在这个例子中,我们定义了一个名为Parent的类,它有一个构造函数__init__,它设置了self.x = 1,并且有一个print_x方法,它打印self.x的值。我们还定义了一个名为Child的类,它继承自Parent,并且在它的构造函数__init__中设置了self.x = 2。我们创建了Parent和Child的实例,并分别调用它们的print_x方法。在Child实例上调用print_x方法时,它会先在Child类中查找x变量,因为在Child类中有x变量的定义,所以它的值为2,而在Parent类中的x变量值为1,所以在Parent实例上调用print_x方法时,它的值为1。
子类要调用父类的函数时怎么写
当子类需要调用父类的函数时,可以使用super()函数进行调用。在子类中使用super()函数,然后指定要调用的父类函数的名称和参数即可调用父类函数。例如,如果有一个父类A和子类B,B需要调用A的foo函数,则可以使用以下代码:
class A:
def foo(self):
print("I am A")
class B(A):
def foo(self):
super().foo()
print("I am B")
b = B()
b.foo()
输出结果:
I am A
I am B
相关推荐
![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)