Python_類的組合

A類與B類之間沒有共同點,但是A類與B類之間有關聯,比如說,醫院類與患者類是兩個完全不同的類,他們之間沒有任何關聯,但是患者是屬於醫院的。此時我們就要用到類的組合來關聯醫院類與患者類。詳細操作詳見下圖:

該部分程式碼為:

class Hospital():      "醫院類"      def __init__(self,name,addr,type):          self.name = name          self.addr = addr          self.type = type        def accpatient(self):          print("%s開始接受患者"%self.name)        def regpatien(self,price):          # print("治療費用為%s"%(price))          price = price + 120.50-150          return  price    class Patient():      "患者類"      def __init__(self,patientname,age,sex,hospital):          self.patientname = patientname          self.age = age          self.sex =sex          self.hospital = hospital        def tohispital(self):          print("%s去%s檢查,檢查為:%s"%(self.patientname,self.hospital.name,self.hospital.regpatien(330)))    #實例化醫院  hospital = Hospital("無錫市人民醫院","江蘇省無錫市人民大道","三甲")  #實例化患者  patient1 = Patient("李明",24,"男",hospital)  #調用患者函數方法  patient1.tohispital()