python中的super函数_python中super().__init__()怎么用

本文详细介绍了Python中super().__init__()的用法。通过示例解释了如何使用super调用父类构造函数,以便在子类初始化时继承父类属性。内容包括不使用、仅初始化子类属性以及使用super初始化时的情况。最后提到了super(class, self).__init__()的另一种形式,用于明确指定子类并转化对象以调用父类的__init__()方法。" 83932361,7413622,Python编程练习:函数、类和编码解析,"['Python编程', '函数使用', '类与对象', '编码解析']
摘要由CSDN通过智能技术生成

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

发布时间:2020-12-08 09:14:33

来源:亿速云

阅读:62

作者:小新

这篇文章给大家分享的是有关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__()怎么用就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值