Pythonで親クラスのメソッドをコールするには?
Pythonでは、`super()`関数を用いて親クラスのメソッドを呼び出す。`super()`関数は、サブクラス内で親クラスのメソッドを呼び出し、親クラスのメソッドの再利用を実現するために使用される。`super()`関数は2つの引数を受け取る:サブクラス名とselfオブジェクト。これらの引数を使用し、`super()`関数は現在のサブクラスの親クラスを見つけ、親クラスの対応するメソッドを呼び出すことができる。以下のサンプルコードを見てみよう。“`pythonclass ParentClass:
def __init__(self):
self.name = “Parent”
def say_hello(self):
print(“Hello from Parent”)class ChildClass(ParentClass):
def __init__(self):
super().__init__() # 親クラスのコンストラクタメソッドを呼び出す
self.name = “Child”
def say_hello(self):
super().say_hello() # 親クラスのメソッドを呼び出す
print(“Hello from Child”)child = ChildClass()child.say_hello()“`出力:“`Hello from ParentHello from Child“`このサンプルでは、`ChildClass`は`ParentClass`を継承する。サブクラスの`__init__`メソッドでは、`super().__init__()`を用いて親クラスのコンストラクタメソッドを呼び出し、サブクラスの`say_hello`メソッドでは、`super().say_hello()`を用いて親クラスのメソッドを呼び出す。