什麼是 OOP?

Python 物件導向程式設計

Alex Yarosh

Content Quality Analyst @ DataCamp

 

程序式程式設計

 

  • 程式碼依步驟序列執行
  • 很適合做資料分析
Python 物件導向程式設計

以序列思考

 

床上的人、咖啡、公事包的連續圖示

 

代表多種活動的各式圖示

Python 物件導向程式設計

 

程序式程式設計

 

  • 程式碼依步驟序列執行
  • 很適合資料分析與腳本

 

物件導向程式設計

 

  • 以物件互動來組合程式碼
  • 很適合打造框架與工具
  • 可維護、可重用的程式碼!
Python 物件導向程式設計

物件作為資料結構

$$\Large{\text{Object = state + behavior}}$$

拿筆電的人形剪影,代表顧客

 

$$\text{\textbf{Encapsulation} - bundling data with code operating on it}$$

Python 物件導向程式設計

類別是藍圖

  • Class :物件的藍圖,定義可能的狀態與行為

customer class

Python 物件導向程式設計

類別是藍圖

  • Class :物件的藍圖,定義可能的狀態與行為

customer class branching out to customer objects

Python 物件導向程式設計

Python 中的物件

  • Python 中萬物皆物件
  • 每個物件都有一個類別
  • type() 查類別
import numpy as np
a = np.array([1,2,3,4])
print(type(a))
numpy.ndarray
Object Class
5 int
"Hello" str
pd.DataFrame() DataFrame
np.mean function
... ...
Python 物件導向程式設計

屬性與方法

狀態 ↔ 屬性
import numpy as np
a = np.array([1,2,3,4])

# shape attribute a.shape
(4,)

 

  • obj. 存取屬性與方法
行為 ↔ 方法
import numpy as np
a = np.array([1,2,3,4])

# reshape method a.reshape(2,2)
array([[1, 2],
       [3, 4]])
Python 物件導向程式設計

物件 = 屬性 + 方法

  • 屬性 ↔ 變數obj.my_attribute

  • 方法 ↔ function()obj.my_method()

import numpy as np
a = np.array([1,2,3,4])
dir(a)                # <--- 列出所有屬性與方法
['T',
 '__abs__',
 ...
 'trace',
 'transpose',
 'var',
 'view']

Python 物件導向程式設計

快速複習一下!

Python 物件導向程式設計

Preparing Video For Download...