Pythonでサブクラスが親クラスのプロパティを継承の方法
Pythonのサブクラスは、親クラスから継承することで親クラスのプロパティを継承できます。この親クラスのコンストラクタを呼び出すには、 super() 関数を使用し、親クラスのプロパティを継承します。以下にサンプルコードを示します。
class ParentClass:
def __init__(self, attribute):
self.attribute = attribute
class ChildClass(ParentClass):
def __init__(self, attribute, child_attribute):
super().__init__(attribute) # 调用父类的构造函数
self.child_attribute = child_attribute
parent = ParentClass("Parent Attribute")
child = ChildClass("Parent Attribute", "Child Attribute")
print(parent.attribute) # 输出 "Parent Attribute"
print(child.attribute) # 输出 "Parent Attribute"
print(child.child_attribute) # 输出 "Child Attribute"
親クラス ParentClass、子クラス ChildClass があり、ChildClass は ParentClass の attribute を継承しています。ChildClass のコンストラクタで super().__init__(attribute) を使って親クラスのコンストラクタを呼び出し、親クラスの attribute を初期化します。さらに、ChildClass 内で child_attribute などの独自の attribute を定義できます。最後に、親クラスのインスタンス parent と子クラスのインスタンス child を作成し、各属性にアクセスします。