知行编程网知行编程网  2022-08-27 20:30 知行编程网 隐藏边栏  30 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python super().__init__()的相关知识,包括python多继承super,以及雪峰python教程这些编程知识,希望对大家有参考作用。


python super().__init__()

super().__init__()在python中是做什么的,相信很多同学还没有搞清楚。说白了,super().__init__()就是继承父类的init方法。你也可以使用 super() 来继承该方法。下面将通过不同的继承和调用来介绍super().__init__()的具体用法。



子类构造函数调用super().




子类构造函数调用super().init()的时候,会从父类继承属性。


三种构造函数的区别:


当子类不做初始化的时候,会自动继承父类的属性;



当子类做初始化(子类中包含新的属性)的时候,子类不会自动继承父类的属性;

当子类做初始化(子类中包含新的属性)的时候,如果子类调用super初始化了父类的构造函数,那么子类会继承父类的属性。

class father:
    def __init__(self, father_attribute="father"):
        self.father_attribute=father_attribute

class child_without_ini(father):
    pass

class child_with_ini(father):
    def __init__(self, child_attribute):
        self.child_attribute=child_attribute

class child_with_super(father):
    def __init__(self,father_attribute,super_attribute):
        self.super_attribute=super_attribute
        super().__init__(father_attribute)

test_class_without_ini=child_without_ini()
test_class_with_ini=child_with_ini('child')
test_class_with_super=child_with_super('new_father','super')


测试:

print(test_class_without_ini.father_attribute)
输出:
father

print(test_class_with_ini.father_attribute)
输出:
AttributeError: 'child_with_ini' object has no attribute 'father_attribute'

print(test_class_with_super.father_attribute)
输出:
new_father


另一种使用方法:

super(class,self).init()

其中class是子类,这段代码的意思是先找到类的父类,然后将类类的对象转化为父类的对象,让“转化”的对象调用自己的__init__( ) 功能 。

class child_with_super(father):
    def __init__(self,father_attribute,super_attribute):
        super(child_with_super, self).__init__(father_attribute)
        self.super_attribute=super_attribute


文章来源于网络,如有雷同,请联系作者。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享