本篇講解 Python Class 類中的多種方法形式:包含 @staticmethod、 @classmethod 和 @abc.abstractmethod,建議讀者們可以一起跟著文章敲一次 code,會有更深入的了解唷。
▍本篇大綱如下:
- Static method 靜態方法:不帶實例,不帶 class 為參數的方法
- Class method 類方法:不帶實例,帶有 class 為參數的方法
- Abstract method 抽象方法:尚未被實作,且繼承 class 一定要用覆寫來實作
Table
一. StaticMethods 靜態方法
▍StaticMethods 使用方法:
- 在 def 函式上加上 @staticmethod
- 不用傳入 self 參數
▍StaticMethods 使用時機:
- 不在需要將 class 實例後才能使用函式,直接像以下範例呼叫 People_StaticMethods.work(4) 即可使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class People_StaticMethods: def __init__(self): pass def sleep(self, sleep_hour): print('Sleeping hours :', sleep_hour) @staticmethod def work(work_hour): print('Working hours :', work_hour) m = People_StaticMethods() m.sleep(3) People_StaticMethods.work(4) >>> Sleeping hours : 3 >>> Working hours : 4 |
二. ClassMethods 類方法
▍ClassMethods 使用方法:
- 在 def 函式上加上 @classmethod
- 必須傳入 class 本身參數,通常大家都會命名為 cls
- 如果要引入 class 其他函式,可以使用 cls().sleep(6)
▍ClassMethods 使用時機:
- 不在需要將 class 實例後才能使用函式,直接像以下範例呼叫 People_ClassMethods.work(5) 即可使用
- 不同於 StaticMethods,因為多引入了 class 本身參數為 cls,可以利用 cls 來 access 其他 class 內的函式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class People_ClassMethods: def __init__(self): pass def sleep(self, sleep_hour): print('Sleeping hours :', sleep_hour) @classmethod def work(cls, work_hour): print('Working hours :', work_hour) cls().sleep(6) People_ClassMethods.work(5) |
三. AbstractMethods 抽象方法
▍AbstractMethods 使用時機:
- 抽象類 (Employee) 的特點是不能實例化,只能被子類繼承
- 任何繼承 Employee 的類,都必須有實現 work 方法,否則會拋出異常,像是 class Max(Employee) 中,只定義了 def sleep(self),沒有定義 work 方法,所以再引用時會出現 Can’t instantiate abstractclass Max with abstract methods work 的錯誤。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import abc # Python 3.4+ class Employee(abc.ABC): @abc.abstractmethod def work(self): return NotImplemented class Andy(Employee): def work(self): print('work') class Max(Employee): def sleep(self): print('sleep') Andy().work() >>> work Max().sleep() >>> Traceback (most recent call last): File "/Users/max/Desktop/python_learning/methods.py", line 77, in <module> Max().sleep() TypeError: Can't instantiate abstractclass Max with abstract methods work |
關於 Python 教學的延伸閱讀:
▍本站的 Python 相關教學:
- [Python教學] 一切皆為物件,到底什麼是物件 Object ?
- [Python教學] 物件導向 – Class 類的 封裝 / 繼承 / 多型
- [Python教學] Class / Static / Abstract Method 初探
- [Python教學] @property 是什麼? 使用場景和用法介紹
- [Python教學] 裝飾詞原理到應用
- [Python 教學] dataclass 是什麼? (python 3.7+)
那 [Python教學] Class / Static /Abstract Method 初探 結束囉,感謝收看!
如有任何問題,歡迎底下留言或私訊,我會盡快回覆您