Dernière activité 9 months ago

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

timmy a révisé ce gist 9 months ago. Aller à la révision

1 file changed, 27 insertions

abc_example.py(fichier créé)

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