python中super().__init__()怎么用-创新互联

这篇文章给大家分享的是有关python中super().__init__()怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

成都创新互联公司是专业的邵阳网站建设公司,邵阳接单;提供网站设计制作、成都网站制作,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行邵阳网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

子类构造函数调用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://csdahua.cn/article/doopis.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流