@abstractmethod 是 Python 標準庫中的一個裝飾器,位於 abc 模組內,用來定義 抽象方法 (abstract methods)。抽象方法是指必須在子類別中實作的方法,而在基類 (abstract base class, ABC) 中只能定義方法名稱和規範,不能有具體的實作內容。
使用 @abstractmethod 可以確保某些方法在子類別中被實作,否則子類別無法被實例化。
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass # 不定義具體實作,只是聲明
@abstractmethod
def move(self):
pass
# Animal 是抽象類別,無法直接實例化
# animal = Animal() # TypeError: Can't instantiate abstract class Animal with abstract methods
class Dog(Animal):
def sound(self):
return "Woof!"
def move(self):
return "Run"
dog = Dog()
print(dog.sound()) # Woof!
print(dog.move()) # Run
範例
class Shape(ABC):
def description(self):
return "This is a shape."
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(4, 5)
print(rect.description()) # This is a shape.
print(rect.area()) # 20
範例
class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardPayment(Payment):
def pay(self, amount):
return f"Paid {amount} using Credit Card."
class PayPalPayment(Payment):
def pay(self, amount):
return f"Paid {amount} using PayPal."
# 支付方式可依不同類別動態改變
def process_payment(payment: Payment, amount):
print(payment.pay(amount))
process_payment(CreditCardPayment(), 100) # Paid 100 using Credit Card.
process_payment(PayPalPayment(), 200) # Paid 200 using PayPal.
範例
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Cat(Animal):
def sound(self):
super().sound() # 調用基類的空方法(僅示例,實際基類方法通常有意義)
return "Meow!"
cat = Cat()
print(cat.sound()) # Meow!
範例
class Vehicle(ABC):
@property
@abstractmethod
def wheels(self):
pass
class Car(Vehicle):
@property
def wheels(self):
return 4
car = Car()
print(car.wheels) # 4
@abstractmethod 是 Python 中用來聲明抽象方法的裝飾器。
它強制子類別實作方法,確保程序設計的規範性和一致性。
抽象基類通常用於定義接口,促進多型行為。