0
1

More than 1 year has passed since last update.

Pythonで子クラスの親クラスを取得する方法

Last updated at Posted at 2023-01-01

概要

Pythonで子クラスの親クラスを取得するには、「inspectモジュール」を用います。Inspectモジュールは、Pythonインタプリタ内で実行されるオブジェクトの情報を取得したり、ソースコードを読み取ったりするライブラリです。Inspectモジュールを使用すると、子クラスの親クラスを取得することができます。

使用例

以下の例では、Inspectモジュールを使用して、子クラスの親クラスを取得しています。

import inspect

class ParentClass:
    def parent_function(self):
        print("Parent Function")

class ChildClass(ParentClass):
    def child_function(self):
        print("Child Function")

# 子クラスの親クラスを取得
parent_class = inspect.getmro(ChildClass)

# 取得した親クラスを出力
print(parent_class)

上記のコードを実行すると、次のように表示されます。

(<class '__main__.ChildClass'>, <class '__main__.ParentClass'>, <class 'object'>)

このように、Inspectモジュールを使用することで、子クラスの親クラスを取得することができます。

0
1
2

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
1