0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの抽象クラスについて

Last updated at Posted at 2025-02-01

Pythonの抽象クラスについて解説

抽象クラスとは?

  • 直接インスタンス化できない クラス
  • 抽象メソッド を定義できる(派生クラスで実装が強制される)
  • 共通のインターフェースを提供するために使われる

抽象クラスの宣言方法

Pythonでは抽象クラスをABCモジュールを使用して宣言可能

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
      
# 抽象クラスを継承
class Circle(Shape):
    def __init__(self, radius):
        self.__radius = radius

    def area(self):
        return 3.14 * self.__radius * self.__radius

circle = Circle(5)
print(circle.area())

動作確認

サブクラスが抽象メソッドを実装しなければ

TypeError が発生する。
インターフェースとしての役割を果たし、バグを防ぐために便利。

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
      
# 抽象クラスを継承
class Circle(Shape):
    def __init__(self, radius):
        self.__radius = radius
TypeError: Can't instantiate abstract class Circle with abstract method area

抽象クラスがABCを継承しなければ

通ってしまう

from abc import ABC, abstractmethod

class Shape():
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.__radius = radius

abstractmethodを定義しなければ

通ってしまう

from abc import ABC, abstractmethod

class Shape(ABC):
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.__radius = radius
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?