1. 程式人生 > >(一)Python入門-6面向對象編程:12組合

(一)Python入門-6面向對象編程:12組合

div print hone 操作 。。 一個 scree 動物 self.

組合:

  “is-a”關系,我們可以使用“繼承”。從而實現子類擁有的父類的方法和屬性。“is-a” 關系指的是類似這樣的關系:狗是動物,dog is animal。狗類就應該繼承動物類。

  “has-a”關系,我們可以使用“組合”,也能實現一個類擁有另一個類的方法和屬性。” has-a”關系指的是這樣的關系:手機擁有 CPU。 MobilePhone has a CPU。

【操作】

#測試組合
import copy
class MobilePhone:
    
def __init__(self,cpu,screen): self.cpu = cpu self.screen = screen class CPU: def calculate(self): print(計算。。。。。) class Screen: def show(self): print(顯示。。。。。) c = CPU() s = Screen() m = MobilePhone(c,s) m.cpu.calculate() #通過組合,調用cpu對象的方法,相當於手機對象間接擁有了‘cpu的方法’
m.screen.show() #通過組合,調用screen對象的方法,相當於手機對象間接擁有了‘screen的方法’

運行結果:

  計算。。。。。
  顯示。。。。。

(一)Python入門-6面向對象編程:12組合