簡明python教程七----物件導向的編程(下)

來源:互聯網
上載者:User

標籤:const   sel   elf   注意   bsp   student   blog   res   tail   

繼承:類之間的類型和子類型關係

代碼重用:SchoolMember類被稱為 基本類或超類,而Teacher和Student類被稱為匯出類或者子類

#!/usr/bin/python#Filename:Inherit.pyclass SchoolMember:    ‘Represents any school member.‘    def __init__(self,name,age):        self.name = name        self.age = age        print ‘(Initialized SchoolMember:%s)‘ %self.name    def tell(self):        ‘Tell my details.‘        print ‘Name:"%s" Age:"%s"‘%(self.name,self.age)class Teacher(SchoolMember):    ‘Represents a teacher.‘    def __init__(self,name,age,salary):        SchoolMember.__init__(self,name,age)        self.salary = salary        print ‘(Initialized Teacher:%s)‘ %self.name    def tell(self):        SchoolMember.tell(self)        print ‘Salary: "%d"‘%self.salaryclass Student(SchoolMember):    ‘Represents a student.‘    def __init__(self,name,age,marks):        SchoolMember.__init__(self,name,age)        self.marks=marks        print ‘(Initialized Student:%s)‘%self.name    def tell(self):        SchoolMember.tell(self)        print ‘Marks:"%d"‘%self.markst=Teacher(‘Mrs.Shrividya‘,40,30000)s=Student(‘Swaroop‘,22,75)print #prints a blank linemembers = [t,s]for member in members:    member.tell()

結果:

(Initialized SchoolMember:Mrs.Shrividya)(Initialized Teacher:Mrs.Shrividya)(Initialized SchoolMember:Swaroop)(Initialized Student:Swaroop)Name:"Mrs.Shrividya" Age:"40"Salary: "30000"Name:"Swaroop" Age:"22"Marks:"75"

注意:為了使用繼承,把基本類的名稱作為一個元組跟在定義類時的類名稱之後。

基本類的__init__方法專門使用self變數調用,這樣我們就可以初始化對象的基本類部分。

記住:python不會自動調用基本類的constructor,需要親自專門調用它。

 

簡明python教程七----物件導向的編程(下)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.