新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:什么是python的構造函數(shù)
Python中的構造函數(shù)是__init__函數(shù)。在Python中,子類如果定義了構造函數(shù),而沒有調(diào)用父類的,那么Python不會自動調(diào)用,也就是說父類的構造函數(shù)不會執(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的構造函數(shù)沒有調(diào)用A的構造函數(shù)。下面我們這樣測試:
>>>import test >>>b = test.B(15) >>>b.age >>>b.name AttributeError: 'B' object has no attribute 'name'
由于B沒有調(diào)用A的構造函數(shù),因此,實例b上面也沒有屬性name,造成訪問出錯。
新聞名稱:創(chuàng)新互聯(lián)Python教程:什么是python的構造函數(shù)
URL鏈接:http://m.fisionsoft.com.cn/article/cceepog.html


咨詢
建站咨詢
