Skip to main content
 首页 » 编程设计

python之我如何组合 wxPython、abc 和元类 mixin

2025年05月04日652php

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

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:元类冲突:派生类的元类必须是其所有基元类的(非严格)子类。我想,“哦,对了,我就用一个 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 的方法是什么?

请您参考如下方法:

在您的第一个示例中,您从 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 的子类,并以 abc.ABCMeta 作为其元类,因为 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.')