资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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://cdkjz.cn/article/pggogh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220