pythonで継承を使ってみる

前回の続きです。Partition.mount()がゴチャゴチャなのは、nilfs2用のコードと、普通のファイルシステム用のコードが一緒になってるからなので、これを分割することにしました。それで、Partitionクラスを継承するNilfs2Partitionクラスを作ることにしたのですが、pythonで子クラスが親クラスのメソッドを呼ぶのには、新旧2通りの方法があるようです。

<新型>

class A(object):
    def __init__(self):
        print 'A'


class B(A):
    def __init__(self):
        super(B, self).__init__()
        print 'B'

<旧型>

class A():
    def __init__(self):
        print 'A'

class B(A):
    def __init__(self):
        A.__init__(self)
        print 'B'

多重継承の場合の親クラスメソッドの探索の仕方が違うらしいのだが、なんだか良くわからない。ただ、新型と旧型を混ぜて使うのは良くない(らしい)。旧型の方が明示的で、キーボードを打つ回数も少なくてすむので良さそうな気がするけど、とりあえず新型を使っておくことにしました。

class Partition(object):
    def mount(self):

        if not (self._flag['is_mount'] or self._attr['mtpt']):
            self._flag['createdir'] = True
            self._attr['mtpt'] = mkdtemp()

        if not self._flag['is_mount']:
            ext = self._extparm + [ self._attr['devnode'], self._attr['mtpt']]
            if exec_command('mount', ext) == 0:
                self._flag['is_mount'] = True


class Nilfs2Partition(Partition):
    def mount(self):
        """ special treatment to mount nilfs2 partition """

        # 既にマウントされているnilfs2パーティション
        # では、nilfs2のスナップショット機能を利用する
        if self._flag['is_mount']:
            self._use_nilfs2_snapshot = True

            # 直近のチェックポイントを変数check_pointに格納します
            lscp_result = Popen(('/usr/bin/lscp', '-r', '-n1', \
                    self._attr['devnode']),stdout=PIPE).communicate()[0]
            check_point = lscp_result.split()[7]

            # nilfs2のsnapshotを作成します
            exec_command('cp2ss', [self._attr['devnode'], check_point])

            # snapshotをマウントする為のオプションを設定します
            self._extparm.extend(["-o", "ro,cp="+check_point])

            self._flag['is_mount'] = False
            self._flag['is_automount'] = False
            self._attr['mtpt'] = None

        super(Nilfs2Partition, self).mount() 

コードを分離したおかげで、場合分けが減って、かなり見た目がスッキリしました。
コード全体は長いのでコチラに置くことにしました。