Son aktivite 9 months ago

ABC(Abstract Base Class)允許定義抽象類別,強制子類別實作特定方法,適用於建立統一的介面規範,確保繼承的類別都遵守特定的行為。

Revizyon b6ac5203059a1f14fa5d05850b2bfedd71531835

abc_example.py Ham
1from abc import ABC, abstractmethod
2
3# 定義抽象類別
4class Animal(ABC):
5 @abstractmethod
6 def make_sound(self) -> str:
7 """所有動物都必須實作此方法"""
8 pass
9
10# 繼承並實作抽象方法
11class Dog(Animal):
12 def make_sound(self) -> str:
13 return "Woof!"
14
15class Cat(Animal):
16 def make_sound(self) -> str:
17 return "Meow!"
18
19# 嘗試建立抽象類別的實例會導致錯誤
20# animal = Animal() # 會拋出錯誤
21
22# 正確使用:實作子類別
23dog = Dog()
24cat = Cat()
25
26print(dog.make_sound()) # Woof!
27print(cat.make_sound()) # Meow!
28