Page cover

abc 【抽象 Class】

簡介


What is abc?

abc module 代表 Abstract Base Classes。它提供了一個在 Python 中定義 abstract base classes (ABCs) 的 framework。這些 Class 可以定義一個 interface (介面)。當其他 built-in 機制 (例如: duck typinghasattr()) 過於靈活或者您想要為不同的 Class 定義通用 API 時,這些功能特別有用。

abc module 使開發人員能夠定義無法實例化的 classes,充當其他 classes 的藍圖。這是透過建立 abstract 方法來完成的,這些方法在 abstract class 中聲明但未實現。然後 subclasses 為這些方法提供具體的實作。

Abstract Base Class 和 Abstract Class 經常互換使用,因為它們具有相同的含義。

在 Python 中,Abstract Base Class (Abstract Class) 是一個無法被實例化的 Class,目的是為 subclass 定義一個公共 interface,它作為其他 Class 的藍圖。該 interface 必須由任何 non-abstract subclass 實現。

How to Use abc?

PYTHON
from abc import ABC, abstractmethod

# Define an Abstract Base Class
class Shape(ABC): 
    @abstractmethod
    def area(self): 
        pass

    @abstractmethod
    def perimeter(self): 
        pass
    
# Implement Subclasses
class Rectangle(Shape): 
    def __init__(self, length, width): 
        self.length = length
        self.width = width

    def area(self): 
        return self.length * self.width

    def perimeter(self): 
        return 2 * (self.length + self.width)

# Create an instance of Rectangle
my_rectangle = Rectangle(3, 4)

# Calculate and print the area and perimeter
print("Rectangle Area: ", my_rectangle.area())            # Output:  12
print("Rectangle Perimeter: ", my_rectangle.perimeter())  # Output:  14

Why Use abc?

  1. 介面的強制執行: 它確保 subclass 實作 base class 的特定方法。

  2. 可讀性和可維護性: 它使開發人員的意圖變得清晰,顯示哪些方法在 class 層次結構中是必不可少的。

  3. 阻止 Class 實例化: 它阻止僅作為 interface 或藍圖的 class 的實例化。

  4. Polymorphism (多態性): 方便多態性的使用,確保所有 child classes 都遵循特定的 interface。

When to Use abc?

  1. 設計 Frameworks 和 Libraries: 在建立 framework 時,您想要定義一組基本方法,以供其他開發人員實作。

  2. 強制 Class Interfaces: 當您需要確保所有 subclasses 都實作某些方法時。

  3. 當需要避免直接 Class 實例化是必要時: 當建立的 classes 是充當 interfaces 或藍圖,而不是具體實施時。

Conclusion

Python 中的 abc module 是一個強大的工具,用於創建定義明確、健壯且易於維護的 class 層次結構。它強制執行 subclasses 中的特定方法,為開發人員提供了明確的契約。

這使得程式碼更可靠、更容易理解。然而,明智地使用 abstract base classes 很重要,因為過度使用可能會導致不必要的僵化程式碼體系結構。

Last updated

Was this helpful?