这里的super(child,child)中,为什么会传两个child
时间: 2023-09-10 21:10:53 浏览: 30
在Python中,`super()`函数用于调用父类的方法。它的语法如下:
```
super([type[, object-or-type]])
```
其中,`type`是一个类,`object-or-type`是一个对象或一个类。如果`object-or-type`是一个对象,则`super()`返回的是该对象所属类的父类;如果`object-or-type`是一个类,则`super()`返回的是该类的父类。
`super()`函数实际上返回了一个`super`对象,该对象包含了父类的方法和属性。我们可以通过该对象来调用父类的方法,例如:
```
class Parent:
def __init__(self):
self.parent_attr = 'parent attribute'
def parent_method(self):
print('Parent method')
class Child(Parent):
def __init__(self):
super().__init__()
self.child_attr = 'child attribute'
def child_method(self):
print('Child method')
c = Child()
c.child_method() # 输出 'Child method'
c.parent_method() # 输出 'Parent method'
print(c.child_attr) # 输出 'child attribute'
print(c.parent_attr) # 输出 'parent attribute'
```
在上面的代码中,我们在`Child`类中使用了`super().__init__()`来调用`Parent`类的构造方法。这里传入两个`child`参数的原因是,`__init__()`方法的第一个参数是`self`,即当前对象。因此,`super().__init__()`中的第一个参数指的是当前对象,第二个参数则是`Child`类本身。这样,`super().__init__()`实际上调用的是`Parent`类的构造方法,传入的参数是`Child`类的对象。这样做的目的是让`Child`类继承`Parent`类的属性和方法。