快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

python中super().__init__()怎么用

这篇文章给大家分享的是有关python中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是子类,这段代码的含义是首先找到class的父类,然后将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

感谢各位的阅读!关于python中super().__init__()怎么用就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!


分享题目:python中super().__init__()怎么用
文章位置:http://6mz.cn/article/pggogh.html

其他资讯