重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊、服務(wù)器等服務(wù)
python要怎樣重寫父類方法?這個問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!
創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括榕城網(wǎng)站建設(shè)、榕城網(wǎng)站制作、榕城網(wǎng)頁制作以及榕城網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,榕城網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到榕城省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
python類的繼承和重寫
繼承父類方法
子類可以直接調(diào)用父類的方法
class Person(): def __init__(self): pass def hello(self): print 'hello' class Student(Person): def __init__(self): pass s = Student() s.hello() # hello
繼承父類屬性
這里要注意, 如果要繼承父類的屬性, 一定要在子類的構(gòu)造函數(shù)里調(diào)用父類的構(gòu)造函數(shù), 否則會報錯無法訪問, 因?yàn)楦割惖臉?gòu)造函數(shù)沒有被調(diào)用, 構(gòu)造函數(shù)中的屬性自然也就沒有被聲明
python學(xué)習(xí)網(wǎng),大量的免費(fèi)python學(xué)習(xí)視頻,歡迎在線學(xué)習(xí)!
這時如果調(diào)用父類的屬性則會報錯, 報錯內(nèi)容為Student實(shí)例沒有name屬性
# coding=utf-8 class Person(): def __init__(self): self.name = '小明' self.age = 18 print('Person class init completed') def hello(self): print 'hello' class Student(Person): def __init__(self): print ('Student class init completed') s = Student() print s.name # Student class init completed # Traceback (most recent call last): # File ".\classDemo.py", line 23, in# print s.name # AttributeError: Student instance has no attribute 'name'
下面是子類在構(gòu)造函數(shù)中調(diào)用父類構(gòu)造函數(shù)的情況, 子類實(shí)例可以訪問父類屬性
# coding=utf-8 class Person(): def __init__(self): self.name = u'小明' self.age = 18 print('Person class init completed') def hello(self): print 'hello' class Student(Person): def __init__(self): Person.__init__(self) print ('Student class init completed') s = Student() print s.name # Person class init completed # Student class init completed # 小明
方法重寫
有時候父類提供的方法不能滿足需求時, 可以在子類中重寫父類的方法
在父類Person中, 構(gòu)造函數(shù)只定義了name和age兩個屬性, print_into()函數(shù)也只打印了name, age這兩個屬性
在子類Student中, 多了一個school屬性, 顯然父類的提供方法功能不夠了, 這時候, 子類就需要對父類的方法進(jìn)行重寫, 擴(kuò)充父類的功能
# coding=utf-8 class Person(object): def __init__(self, name, age): self.name = name self.age = age def print_info(self): print 'name: ', self.name print 'age: ', self.age class Student(Person): def __init__(self, name, age, school): Person.__init__(self, name, age) self.school = school def print_info(self): super(Student, self).print_info() # python3 中可直接使用super() # Python2 一般為super(class, self), 且class要為新類 # 新類就是由內(nèi)置類型派生出來的類 print 'school: ', self.school s = Student(u'小明', 18, u'家里蹲大學(xué)') s.print_info() # name: 小明 # age: 18 # school: 家里蹲大學(xué)
感謝各位的閱讀!看完上述內(nèi)容,你們對python要怎樣重寫父類方法大概了解了嗎?希望文章內(nèi)容對大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。