親クラス

親クラス(Parent Class)は、オブジェクト指向プログラミング(OOP)において、継承(Inheritance)に関連する概念です。親クラスは、他のクラスによって継承されるクラスの元となるクラスを指します。親クラスは、サブクラス(子クラスまたは派生クラスとも呼ばれる)に共通の属性とメソッドを提供し、サブクラスはこれらの属性とメソッドを継承して利用できます。

以下は、簡単なPythonのクラス継承の例です。ParentClass は親クラスであり、ChildClass はその親クラスを継承するサブクラスです。

python
class ParentClass: def __init__(self, name): self.name = name def greet(self): return f"Hello, I'm {self.name} from the ParentClass." class ChildClass(ParentClass): def greet(self): return f"Hello, I'm {self.name} from the ChildClass." # 親クラスのインスタンスを作成 parent = ParentClass("Alice") print(parent.greet()) # 親クラスのgreetメソッドを呼び出し # サブクラスのインスタンスを作成 child = ChildClass("Bob") print(child.greet()) # サブクラスのgreetメソッドを呼び出し

この例では、ParentClass は親クラスで、ChildClass はそのサブクラスです。サブクラスは ParentClass を継承し、ParentClass の属性とメソッドを使用できます。サブクラスは親クラスの属性やメソッドを拡張、変更、またはオーバーライドすることができます。

親クラスは、共通の機能や特性を提供し、コードの再利用と整理に役立ちます。サブクラスは、親クラスからの継承によって、親クラスの機能を拡張またはカスタマイズできます。これにより、オブジェクト指向プログラムの柔軟性と保守性が向上し、コードの効率が向上します。