定義抽象基類,規范介面內部方法執行順序
在進階篇中,沒專門提過抽象基類,在這里順便就提一下
抽象基類的核心特征:不能被直接實體化
相反,抽象基類和元類一樣,一般都被當做頂層基類使用,派生類必須實作抽象類中指定的方法,且方法名也必須保持一致
抽象基類的主要用途:從一種高層次上規范編程介面
話不多說,直接上代碼
1 import abc 2 3 4 class Template(metaclass=abc.ABCMeta): 5 @abc.abstractmethod 6 def pre(self): 7 ... 8 9 @abc.abstractmethod 10 def execute(self): 11 ... 12 13 def func(self): 14 """定義內部介面執行順序""" 15 self.pre() 16 self.execute() 17 18 19 class Valley(Template): 20 def pre(self): 21 print("預執行") 22 23 def execute(self): 24 print("正式執行") 25 26 27 if __name__ == '__main__': 28 Valley().func()
output:
預執行
正式執行
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/511989.html
標籤:其他
下一篇:關于架構師:角色、能力和挑戰
