新聞中心
對(duì)于python里的super().__init__()有什么作用,相信有很多同學(xué)沒(méi)有弄清楚。直白的說(shuō)super().__init__(),就是繼承父類(lèi)的init方法,同樣可以使用super()去繼承的方法。下面通過(guò)不同的繼承并調(diào)用,向大家介紹super().__init__()的具體使用方法。

我們提供的服務(wù)有:成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、成都外貿(mào)網(wǎng)站建設(shè)、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、甕安ssl等。為上1000家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢(xún)和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的甕安網(wǎng)站制作公司
子類(lèi)構(gòu)造函數(shù)調(diào)用super().
子類(lèi)構(gòu)造函數(shù)調(diào)用super().init()的時(shí)候,會(huì)從父類(lèi)繼承屬性。
三種構(gòu)造函數(shù)的區(qū)別:
當(dāng)子類(lèi)不做初始化的時(shí)候,會(huì)自動(dòng)繼承父類(lèi)的屬性;
當(dāng)子類(lèi)做初始化(子類(lèi)中包含新的屬性)的時(shí)候,子類(lèi)不會(huì)自動(dòng)繼承父類(lèi)的屬性;
當(dāng)子類(lèi)做初始化(子類(lèi)中包含新的屬性)的時(shí)候,如果子類(lèi)調(diào)用super初始化了父類(lèi)的構(gòu)造函數(shù),那么子類(lèi)會(huì)繼承父類(lèi)的屬性。
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')
測(cè)試:
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是子類(lèi),這段代碼的含義是首先找到class的父類(lèi),然后將class類(lèi)的對(duì)象轉(zhuǎn)化為父類(lèi)的對(duì)象,讓后讓這個(gè)“被轉(zhuǎn)化”的對(duì)象調(diào)用自己的__init__()函數(shù)。
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
文章來(lái)源于網(wǎng)絡(luò),如有雷同,請(qǐng)聯(lián)系作者。
網(wǎng)站欄目:創(chuàng)新互聯(lián)Python教程:pythonsuper().__init__()
標(biāo)題URL:http://m.fisionsoft.com.cn/article/ccdiccj.html


咨詢(xún)
建站咨詢(xún)
