Irohabook
0
8281

Pythonの継承:子クラスは親クラスのインスタンス変数を継承する

Python で同じインスタンス変数やインスタンスメソッドをもつクラスが大量に出てきたら、そろそろクラスを継承するときかもしれない。

class News:
    def __init__(self, title):
        self.title = title

    def get_news_title(self):
        print('ニュース記事 ' + self.title)


class Blog:
    def __init__(self, title):
        self.title = title

    def get_blog_title(self):
        print('ブログ記事 ' + self.title)

上のコードはどことなく気持ちが悪い。なぜか? title が共通しているからだ。同じものを何回も書くとき、そのコードは修正できる可能性がある。

メモ: 単なる見映えのために共通化すると、かえって全体最適化に反する場合がある

Python クラスの継承

News と Blog を抽象化して Page というクラスを作り、そこに title を入れる。

class Page:
    def __init__(self, title):
        self.title = title


class News(Page):
    def get_news_title(self):
        print('ニュース記事 ' + self.title)


class Blog(Page):
    def get_blog_title(self):
        print('ブログ記事 ' + self.title)


news = News('Python')
blog = Blog('Python')

news.get_news_title()
blog.get_blog_title()

出力:

ニュース記事 Python
ブログ記事 Python

News や Blog は Page を具体化したものにすぎない。 News は子クラス、 Page は親クラスになる。子クラスはカッコの中に親クラスを書く。

class News(Page):

これをクラスの継承という。

子クラスは親クラスのだいたいすべてを引き継ぐ。つまり子クラス News は title などのインスタンス変数をもつ。これらは News で直接定義されているわけでない。あくまでも親クラス Page を通してもっているにすぎない。

コンストラクタで継承を確認する

class Page:
    def __init__(self, title):
        print('Page コンストラクタ')
        self.title = title


class News(Page):
    def get_news_title(self):
        print('ニュース記事 ' + self.title)


class Blog(Page):
    def get_blog_title(self):
        print('ブログ記事 ' + self.title)


news = News('Python')
news.get_news_title()

News のオブジェクトを宣言するとき Page のコンストラクタが動く。上の出力はこうなる。

Page コンストラクタ
ニュース記事 Python

Python の dict でインスタンス変数を確認する

オブジェクトのインスタンス変数をチェックするには dict を使う。継承したオブジェクトのインスタンス変数を確認してみよう。

class Page:
    def __init__(self, title):
        print('Page コンストラクタ')
        self.title = title


class News(Page):
    def get_news_title(self):
        print('ニュース記事 ' + self.title)


class Blog(Page):
    def get_blog_title(self):
        print('ブログ記事 ' + self.title)


news = News('Python')
news.get_news_title()

print(news.__dict__)

出力:

Page コンストラクタ
ニュース記事 Python
{'title': 'Python'}

きちんと {'title': 'Python'} という辞書が返っている。子クラスのオブジェクトに親クラスのインスタンス変数が入っていることがわかる。

次の記事

クラスとオブジェクト