def __init__(self): super().__init__()
时间: 2023-08-07 19:08:36 浏览: 38
这段代码是一个类的初始化方法(`__init__`),它继承了父类的初始化方法(`super().__init__()`)。在子类的`__init__`方法中调用`super().__init__()`可以确保子类继承了父类的属性和方法。这样做是为了在子类中添加额外的属性和方法时,仍然能够保留父类的功能。
相关问题
如下代码实现了继承,请补全代码: class Animal: _total = 0 def __init__(self): ① ._total += 1 class Dog(Animal): __dtotal = 0 def __init__(self): super().__init__() ② .__dtotal += 1 @ ③ . def show(cls): print("animal: ", super()._total, ", dog:", cls.__dtotal) class Bird(Animal): __btotal = 0 def __init__(self): super().__init__() ④ .__btotal += 1 def show(self): print("animal:", super()._total, ", bird:", ⑤ .__btotal) d1 = Dog(); d2 = Dog(); b1 = Bird() d1.show(); b1.show()
答案如下:
class Animal:
_total = 0
def __init__(self):
Animal._total += 1
class Dog(Animal):
__dtotal = 0
def __init__(self):
super().__init__()
Dog.__dtotal = 1
@classmethod
def show(cls):
print("animal: ", super()._total, ", dog:", cls.__dtotal)
class Bird(Animal):
__btotal = 0
def __init__(self):
super().__init__()
Bird.__btotal = 1
def show(self):
print("animal:", super()._total, ", bird:", Bird.__btotal)
d1 = Dog()
d2 = Dog()
b1 = Bird()
d1.show()
b1.show()
def __init__(self): super(self).__init__()
这段代码中的 `super(self).__init__()` 是错误的用法。在调用 `super()` 函数时,第一个参数应该是当前类的类名,而不是实例对象 `self`。
正确的用法应该是 `super(ClassName, self).__init__()`,其中 `ClassName` 是当前类的类名。例如:
```python
class Main(Parent):
def __init__(self):
super(Main, self).__init__()
```
在这个例子中,`Main` 类继承自 `Parent` 类,并在其构造函数中调用了父类的构造函数。通过调用 `super(Main, self).__init__()`,`Main` 类可以继承父类的属性和方法,并在其自己的构造函数中添加自己的属性和方法。
需要注意的是,Python 3 中的 `super()` 函数可以省略第一个参数,如果省略了第一个参数,Python 会自动根据当前类和实例对象来确定要调用的父类。例如:
```python
class Main(Parent):
def __init__(self):
super().__init__()
```
在这个例子中,我们省略了第一个参数,Python 会自动根据 `Main` 类和实例对象来确定要调用的父类。