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!