super().init() 的使用与理解
文章目录
一、派生类中调用基类的__init__()方法
在派生类中定义__init__()方法时候,不会自动调用基类的__init__()方法。
代码如下(示例):
ss Fruit: # 定义水果类(基类)
def __init__(self, color='绿色'):
self.color = color # 定义类属性
def harvest(self):
print('水果原来是: ' + self.color + '的 !!!') # 输出的是类属性color
class Apple(Fruit): # 定义苹果类(派生类)
def __init__(self):
# super().__init__() # 调用基类的__init__()方法
print('我是青苹果')
def harvest(self): # 复写了基类的方法
print('青苹果现在是: ' + self.color + '的 !!!') # 输出的是类属性color
fruit = Fruit() # 创建类的实例(苹果)
fruit.harvest() # 调用基类的harvest的
apple = Apple() # 创建类的实例(苹果)
apple.harvest() # 调用派生类的harvest的
执行上面代码后系统报错,说没有color这个属性
二、super().init() 的使用
#super().init() 只需要把注释的这行代码改回来就可以了
总结
要让派生派调用基类的__init__()方法进行必要的初始化需要在派生类中使用super() . __ init__()方法。也就是说你不要super方法你就不能使用基类的__init__()那时候定义的变量(属性)
super().__ init__() 使用父类的初始化方法来初始化子类,也就是说,子类继承了父类的所有属性和方法。父类属性自然会用父类方法来进行初始化。