Python 组合模式异常处理与 pylint

1 投票
5 回答
2123 浏览
提问于 2025-04-15 12:44

我正在以这种方式实现一个组合模式:

1) “抽象”组件是:

class Component(object):
    """Basic Component Abstraction"""
    def __init__(self, *args, **kw):
        raise NotImplementedError("must be subclassed")

    def status(self):
        """Base Abstract method"""
        raise NotImplementedError("must be implemented")

2) 一个叶子节点:

class Leaf(Component):
    """Basic atomic component
    """
    def __init__(self, *args, **kw):
        self.dict = {}

    def status(self):
        """Retrieves properties
        """
        return self.dict

问题是,pylint自然会生成这个警告:

Leaf.__init__: __init__ method from base class 'Component' is not called

但是在我的叶子节点中,我无法调用:

def __init__(self, *args, **kw):
    Component.__init__(self, *args, **kw)
    self.dict = {}

否则会引发异常。

我必须忽略pylint的警告,还是说我的代码有问题?

5 个回答

2

把你的类名从 Component 改成 AbstractComponent 会有帮助。而且,如果基类不应该被子类调用,就不要在基类里提供 __init__ 方法。

2

还有一个建议可以补充Markus的想法:

如果你真的需要这样做,我建议你使用 __new __ 方法,并检查对象的类型。当类型是“Component”时,你可以抛出一个异常:

class Component(object):
"""Basic Component Abstraction"""

def __new__(objType, *args, **kwargs):
    if objType == Component:
       raise NotImplementedError("must be subclassed")
    return object.__new__(type, *args, **kwargs)

当创建一个子类时,objType 将不等于 Component,这样一切就没问题了!

5

抽象初始化器其实不是个好主意。你的代码可能会发展到需要在根组件里进行一些初始化操作。即使你现在不需要,为什么还要强制实现这个初始化器呢?对于某些子类来说,留一个空的初始化器可能就足够了。

如果你不想让Component类的实例存在,可以在初始化器里检查一下:

class Component(object):
    def __init__(self, **kwargs):
        assert type(self) != Component, "Component must not be instantiated directly"

class Leaf(Component):
    def __init__(self, some, args, **kwargs):
        # regular initialization
        Component.__init__(self, **kwargs)

撰写回答