abc_example.py
· 592 B · Python
Ham
from abc import ABC, abstractmethod
# 定義抽象類別
class Animal(ABC):
@abstractmethod
def make_sound(self) -> str:
"""所有動物都必須實作此方法"""
pass
# 繼承並實作抽象方法
class Dog(Animal):
def make_sound(self) -> str:
return "Woof!"
class Cat(Animal):
def make_sound(self) -> str:
return "Meow!"
# 嘗試建立抽象類別的實例會導致錯誤
# animal = Animal() # 會拋出錯誤
# 正確使用:實作子類別
dog = Dog()
cat = Cat()
print(dog.make_sound()) # Woof!
print(cat.make_sound()) # Meow!
| 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! |
| 28 |