前言
程式碼的重複利用在長期開發程式是相當重要的一環。
(大家應該都不希望每次有同樣的要求時,都要重寫一次程式碼吧XD)
因此,我們撰寫程式碼時,特別是需要長期使用的,
我們會特別把重複性高的功能拉出來,讓我們程式碼的可重用性 (code reusability) 提高。
code reuse (code reusability、程式碼可重用性)
要說 code reusability 之前,我們可以先理解 SRP (單一職責原則、Single Responsibility Principle)
可參考:【程式優化】OOP (物件導向程式設計、Object Oriented Programming) – SRP (單一職責原則、Single Responsibility Principle)
SRP 所提倡的概念是將程式碼的功能單一化,單一化後的功能我們很容易進行再次的使用,
我們一樣舉 SRP 中所提到的例子。
class Dogs:
# 建構式
def __init__(self, name, sex):
self.name = name # 姓名屬性
self.sex = sex # 性別屬性
# 方法(Method)
def angry(self):
print("The dog is angry.")
def hungry(self):
self.angry()
def hurt(self):
self.angry()
我們可以指藉由修改 angry(self)
這個函數,
同時讓hungry(self)
、 hurt(self)
獲得更新版生氣函數的功能。
此外如果要增加新的現象 (例如:主人打呼),狗狗也會生氣,
透過良好的 code reusability,我們可以很容易又有效率地實現它。
Reference
https://wadehuanglearning.blogspot.com/2019/12/blog-post.html
http://teddy-chen-tw.blogspot.com/2014/04/solid.html
https://ithelp.ithome.com.tw/articles/10191955
https://www.learncodewithmike.com/2020/01/python-class.html
https://www.learncodewithmike.com/2020/01/python-method.html
https://weilihmen.medium.com/%E9%97%9C%E6%96%BCpython%E7%9A%84%E9%A1%9E%E5%88%A5-class-%E5%9F%BA%E6%9C%AC%E7%AF%87-5468812c58f2