这篇文章给大家分享的是有关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__()怎么用就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.py.cn/jishu/jichu/21716.html