新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:什么是python的構(gòu)造函數(shù)
Python中的構(gòu)造函數(shù)是__init__函數(shù)。在Python中,子類如果定義了構(gòu)造函數(shù),而沒有調(diào)用父類的,那么Python不會(huì)自動(dòng)調(diào)用,也就是說父類的構(gòu)造函數(shù)不會(huì)執(zhí)行。

比如有test.py的module文件:
class A: def __init__(self, name): self.name = name class B(A): def __init__(self, age): self.age = age
子類B繼承自A,但是子類B的構(gòu)造函數(shù)沒有調(diào)用A的構(gòu)造函數(shù)。下面我們這樣測(cè)試:
>>>import test >>>b = test.B(15) >>>b.age >>>b.name AttributeError: 'B' object has no attribute 'name'
由于B沒有調(diào)用A的構(gòu)造函數(shù),因此,實(shí)例b上面也沒有屬性name,造成訪問出錯(cuò)。
當(dāng)前文章:創(chuàng)新互聯(lián)Python教程:什么是python的構(gòu)造函數(shù)
URL標(biāo)題:http://www.dlmjj.cn/article/cceepog.html


咨詢
建站咨詢
