【问题标题】:How do I combine wxPython, abc, and a metaclass mixin?如何结合 wxPython、abc 和元类 mixin?
【发布时间】:2013-06-24 23:19:14
【问题描述】:

我有一个其他类应该继承的基类:

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。我想,“哦,对了,我就用一个 mixin”:

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

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

没有变化:仍然是相同的 TypeError 消息。我怀疑我在这里使用ABCMeta 遗漏了一些明显的东西;这看起来不像是 wxPython 特有的错误。我究竟做错了什么?有没有更好的方法来解决同样的问题?

编辑:在与一位同事的对话中向我指出不能混合元类。由于wx.ToolBar 显然是从sip.wrappertype 派生的,看来没有办法做到这一点。在这里处理“抽象方法”方法的另一种仍然是 Pythonic 的方法是什么?

【问题讨论】:

    标签: python python-3.x wxpython abc


    【解决方案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
    

    虽然仔细看一下,但您似乎不能以 abc.ABCMeta 作为元类来定义 wx.Toolbar 的子类,因为 wx.Toolbar 是 bultins.type 以外的元类的实例。但是,您可以从 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.')
    

    【讨论】:

    • 嗯,不错;这实际上是我最初拥有的(在这里重新创建代码时忘记了)。唉,似乎与 wxPython 存在某种奇怪的冲突,因为这不起作用。
    • 那么看起来 wx.ToolBar 不是类型的直接实例,在这种情况下你不走运;据我所知,在 Python 中没有一个很好的方法来组合元类。
    猜你喜欢
    • 2013-11-22
    • 1970-01-01
    • 2014-07-07
    • 2021-07-15
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    相关资源
    最近更新 更多