Python のコンストラクタを使用して、サブクラスがスーパークラスを呼び出す方法

Python では、コンストラクタ内でスーパークラスのメソッドを呼び出すことで、サブクラスからスーパークラスのメソッドを呼び出すことが可能です。以下に例を示します。

class ParentClass:
    def __init__(self, x):
        self.x = x

    def print_x(self):
        print('X:', self.x)


class ChildClass(ParentClass):
    def __init__(self, x, y):
        super().__init__(x)  # 调用父类的构造函数
        self.y = y

    def print_y(self):
        print('Y:', self.y)


child = ChildClass(10, 20)
child.print_x()  # 调用父类方法
child.print_y()  # 调用子类方法

上の例では、ParentClass は、__init__() のコンストラクタと、x の値を出力する print_x() のメソッドを持つ親クラスです。ChildClass は、ParentClass から継承する子クラスであり、__init__() のコンストラクタと、y の値を出力する print_y() のメソッドも持っています。

ChildClass のコンストラクタで、super().__init__(x)を使って親クラス ParentClass のコンストラクタを呼び出し、引数の x を親のコンストラクタに渡します。これにより、子クラスは親クラスの属性とメソッドを継承します。

最後に、ChildClassのインスタンスchildを作成し、print_x()メソッドとprint_y()メソッドを呼び出して、親クラスのx値と子クラスのy値をそれぞれ出力する。

bannerAds