python クラスを継承する

python クラスを継承する

pythonで、他のクラスのメソッドを使用することのできる継承クラスを作成するサンプルコードを記述してます。pythonのバージョンは3.8.5を使用してます。

環境

  • OS windows10 pro 64bit
  • python 3.8.5

クラス継承

pythonの場合、別のクラスを継承する場合は
「class クラス名(継承するクラス名)」と記述します。

class Parent:
    # コンストラクタ _を前後に2つ
    def __init__(self):
        print ('Parentコンストラクタ')

    # pythonではメソッドには引数が必要
    def msg(self): 
        print ('Parentメソッド')

# 継承はclass クラス名(基底クラス名)
class Child(Parent):
    # 自身のメソッド
    def hello(self):
        print("Childメソッド")

# インスタンスを生成 継承したクラスのコンストラクタが実行される
child = Child()
# Parentコンストラクタ

# 自身のクラスのメソッド
child.hello()
# Childメソッド

# 継承したクラスのmsg()メソッド実行
child.msg()
# Parentメソッド

オーバーライド

また、継承したクラスのメソッドをオーバーライドするには、同じ名前のメソッドを定義します。

class Parent:
    # コンストラクタ _を前後に2つ
    def __init__(self):
        print ('Parentコンストラクタ')

    # pythonではメソッドには引数が必要
    def msg(self): 
        print ('Parentメソッド')

# 継承はclass クラス名(基底クラス名)
class Child(Parent):
    # msgメソッドを定義
    def msg(self):
        print("Childメソッド")

# インスタンスを生成 継承したクラスのコンストラクタが実行される
child = Child()
# Parentコンストラクタ

# オーバーライドしたクラスのmsg()メソッド実行
child.msg()
# Parentメソッド

多重継承

pythonは多重継承することも可能で、
「class クラス名(継承するクラス名,継承するクラス名)」と記述します。

コンストラクタは、左側のクラスが優先されるようです。

class Parent1:
    
    def __init__(self):
        print ('Parent1コンストラクタ')

    
    def msg1(self): 
        print ('Parent1メソッド')

class Parent2:
    
    def __init__(self):
        print ('Parent2コンストラクタ')
    
    def msg2(self): 
        print ('Parent2メソッド')

# 継承はclass クラス名(基底クラス名)
class Child(Parent1,Parent2):
    # 自身のメソッド
    def hello(self):
        print("Childメソッド")

# インスタンスを生成 継承したクラスのコンストラクタが実行される
child = Child()
# Parent1コンストラクタ

# 多重継承したクラスのmsg()メソッド実行
child.msg1()
# Parent1メソッド

# 多重継承したクラスのmsg()メソッド実行
child.msg2()
# Parent2メソッド