2

他のクラスが継承する基本クラスがあります。

class AppToolbar(wx.ToolBar):
    ''' Base class for the Canary toolbars '''

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # ... a few common implementation details that work as expected...

        self._PopulateToolbar()
        self.Realize()

基本クラスは を実装していません (実装できません) _PopulateToolbar()。抽象メソッドである必要があります。そのため、使用abcするのが良い計画だと考えたので、これを試しました:

class AppToolbar(wx.ToolBar, metaclass=abc.ABCMeta):
     # ... as above, but with the following added
     @abc.abstractmethod
     def _PopulateToolbar():
         pass

当然のことながら、これを実行しようとするとTypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. 私は「ああ、そうだ、ミックスインを使うだけだ」と思った:

class PopulateToolbarMixin(metaclass=ABCMeta):
    @abstractmethod
    def _PopulateToolbar(self):
        pass

PopulateToolbarMixin.register(wx.ToolBar)
PopulateToolbarMixin.register(AppToolbar)

変更なし: 同じTypeErrorメッセージです。ABCMetaここを使用すると、明らかな何かが欠けていると思います。これは wxPython 固有のエラーではないようです。私は何を間違っていますか?同じ問題にアプローチするより良い方法はありますか?

編集:同僚との会話で、メタクラスを混在させることはできないと指摘されました。wx.ToolBarどうやら から派生しているためsip.wrappertype、これを行う方法はないようです。ここで「抽象メソッド」アプローチを処理する別のまだ Pythonic な方法は何ですか?

4

1 に答える 1

1

wx.ToolBar と abc.ABCMeta から継承する最初の例では、AppToolbar を abc.ABCMeta のサブクラスにしたくないため、AppToolbar をそのインスタンスにしたいと考えています。これを試して:

class AppToolbar(wx.ToolBar, metaclass=abc.ABCMeta):
     # ... as above, but with the following added
     @abc.abstractmethod
     def _PopulateToolbar():
         pass

これをもう少し詳しく見てみると、wx.Toolbar は bultins.type 以外のメタクラスのインスタンスであるため、abc.ABCMeta をメタクラスとして wx.Toolbar のサブクラスを定義することはできないようです。ただし、AppToolbar._PopulateToolbar から抽象的な動作を得ることができます。

class AppToolbar(wx.ToolBar):
     def _PopulateToolbar():
         ''' This is an abstract method; subclasses must override it. '''

         raise NotImplementedError('Abstract method "_PopulateToolbar" must be overridden before it can be called.')
于 2013-06-24T23:44:57.753 に答える