timmy revisó este gist 9 months ago. Ir a la revisión
1 file changed, 27 insertions
abc_example.py(archivo creado)
| @@ -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! | |
Siguiente
Anterior