親クラスのコンストラクタをそのままsuper()して引き継ぐ

はじめに

作成中のPythonETLで、社内共通テンプレートのソースコードを継承して、子クラスで追加の処理を書いていく必要があった。

子クラスの初期化時に、親クラスの初期化処理を引き継ぐ必要があったので、そのサンプルについて書いていく。

サンプルのソースコード

overrideディレクトリに、parent.pyとchild.pyを作成した。

parent.py

# 親クラス(SuperClass)
class Animal:
    def __init__(self, name):
        self.name = name
        print(f"Animal constructor called: {self.name}")

child.py

from parent import Animal

# 子クラス(SubClass)
class Dog(Animal):
    def __init__(self, name):
        # 親クラスのコンストラクタをそのまま引き継ぐ
        super().__init__(name)
        print(f"Dog constructor called: {self.name}")

# 実行してみる
my_dog = Dog("Pochi")

実行結果

(venv) Mac:python shibatahiroshitaka$  /usr/bin/env /Users/shibatahiroshitaka/Downloads/python/venv/bin/python /Users/shibatahiroshitaka/.vscode/extensions/ms-python.debugpy-2025.4.1-darwin-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher 63840 -- /Users/shibatahiroshitaka/Downloads/python/override/child.py 
Animal constructor called: Pochi
Dog constructor called: Pochi

処理の流れ

child.pyの11行目でPochiを引数に渡したDogクラスの初期化が行われる。Dogクラスでは、Animalクラスの初期化がそのまま行われる。

parent.pyの4行目でself.nameにPochiが代入される。5行目で「Animal constructor called: Pochi」がコンソールに出力される。

child.pyの8行目で「Dog constructor called: Pochi」がコンソールに出力される。

Dogクラスが呼ばれる

引数には「Pochi」が渡されている。

super()でAnimalクラスの初期化がそのまま呼ばれる

「Animal constructor called: Pochi」がコンソールに出力される

「Dog constructor called: Pochi」がコンソールに出力される

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です