python-類的組合和使用

來源:互聯網
上載者:User

標籤:inf   self   組件   之間   lap   spl   技術   display   end   

組合

1、python中除了類與類的繼承關係外,還有組合的關係。

什麼是組合——就是解決一個類作為另一個類的屬性。

       是解決一個類【有】什麼的問題。eg:學生【有】課程,老師【有】課程。

繼承與組合的區別:

1、繼承——》解決的問題:是什麼【是】什麼的關係:eg 學生【是】人類,老師【是】人類。

      用法:當一個類中有很多相同的功能,用類提取這些功能,形成基類。

2、組合——》解決的問題:是什麼【有】什麼的關係:eg 學生【有】課程、老師【有】課程

      用法:當一個類中【有】某些功能的時候。eg:老師有生日、老師有學生。

 

class People:    def __init__(self,name,age,sex):        self.name=name        self.age=age        self.sex=sexclass Course:    def __init__(self,name,period,price):        self.name=name        self.period=period        self.price=price    def tell_info(self):        print(‘<%s %s %s>‘ %(self.name,self.period,self.price))class Teacher(People):    def __init__(self,name,age,sex,job_title):        People.__init__(self,name,age,sex)        self.job_title=job_title        self.course=[]        self.students=[]class Student(People):    def __init__(self,name,age,sex):        People.__init__(self,name,age,sex)        self.course=[]egon=Teacher(‘egon‘,18,‘male‘,‘沙河霸道金牌講師‘)s1=Student(‘牛榴彈‘,18,‘female‘)python=Course(‘python‘,‘3mons‘,3000.0)linux=Course(‘python‘,‘3mons‘,3000.0)#為老師egon和學生s1添加課程egon.course.append(python)egon.course.append(linux)s1.course.append(python)#為老師egon新增學生s1egon.students.append(s1)#使用for obj in egon.course:    obj.tell_info()
組合的用法

 

總結:

當類之間顯著不同,且較小的類是較大的類的組件時,用組合比較好。

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.