Python の子クラスがどのように親クラスを呼び出すか

Python では、super() 関数を使用して親クラスのメソッドを呼び出せます。super() 関数は一時オブジェクトを返し、そのオブジェクトを使用して親クラスのメソッドを呼び出すことができます。

以下に例を示します。

class ParentClass:
def __init__(self):
print("父类的初始化方法")
def some_method(self):
print("父类的方法")
class ChildClass(ParentClass):
def __init__(self):
super().__init__()  # 调用父类的初始化方法
def some_method(self):
super().some_method()  # 调用父类的方法
print("子类的方法")
child = ChildClass()
# 输出:
# 父类的初始化方法
child.some_method()
# 输出:
# 父类的方法
# 子类的方法

上で示した例では、ChildClassはParentClassを継承しています。ChildClassの__init__メソッド内では、super().__init__()を使用して親クラスのParentClassの__init__メソッドを呼び出すことができます。ChildClassのsome_methodメソッド内では、super().some_method()を使用して親クラスのParentClassのsome_methodメソッドを呼び出すことができます。

bannerAds