LoginSignup
3
3

More than 5 years have passed since last update.

無駄な関数を、継承を使って実装しないようにする

Posted at

前の投稿
newとかinitとかを再整理

class SheetData():
    def __init__(self, shtnam, toprow, keyclm, lftclm, rgtclm):
        self.data = get_sheet_data(shtnam, toprow, keyclm, lftclm, rgtclm)
        self.clmcnt = rgtclm - lftclm + 1

    def getRecordCount(self):
        return len(self.data) / self.clmcnt

    def get(self, rowidx, clmidx):
        return self.data[rowidx * self.clmcnt + clmidx]
class CategoryStructure(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "__instance__"):
            cls.__instance__ = super(CategoryStructure, cls).__new__(cls, *args, **kwargs)
            cls._data = SheetData(u"カテゴリ構成", 3, 2, 2, 5)
        return cls.__instance__

    def getRecordCount(self):
        return self._data.getRecordCount()

    def get(self, rowidx, clmidx):
        return self._data.get(rowidx, clmidx)

のように書いたけど、CategoryStructureに、SheetDataで実装している関数getRecordCount()とかget()が実装しているのが嫌なので、継承(多重継承)でどうにかできないか調べてみた。

下記のサイトを参考にした。
- Python の super のメリットとデメリット - methaneのブログ

継承元のinit()は、明示的に呼び出す必要がある。
上記で書いたサイトに、多重継承の場合、init()に引数(self以外の引数)を指定する場合、継承元のクラスを明示的に指定する必要があるとのことなのでそのように実装。
(念のため、クラス名を指定しないで実装したら、自分が期待したように動作しなかった(SheetDataのinitが呼び出されなかった))

変更は、CategoryStructureクラスだけ。

class CategoryStructure(object, SheetData):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "__instance__"):
            cls.__instance__ = super(CategoryStructure, cls).__new__(cls, *args, **kwargs)
        return cls.__instance__

    def __init__(self, *args, **kwargs):
        #selfはインスタンスオブジェクトだけどシングルトンで実装しているので下記の判定は
        #上手く動く
        if not hasattr(self, "data"):
            #super(CategoryStructure, self).__init__(self, u"カテゴリ構成", 3, 2, 2, 5)
            #上記(コメント)だと、SheetData.__init__()が動かない
            #クラス名を明示的に指定して__init__()を呼び出す
            SheetData.__init__(self, u"カテゴリ構成", 3, 2, 2, 5)

まだまだ手探り状態だけど、取り敢えず、すっきりした。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3