Python 复合模式异常处理和 pylint

DrF*_*k3n 1 python pylint composite

我以这种方式实现复合模式:

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")
Run Code Online (Sandbox Code Playgroud)

2)一片叶子:

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

    def status(self):
        """Retrieves properties
        """
        return self.dict
Run Code Online (Sandbox Code Playgroud)

问题是 pylint 当然会生成以下警告:

Leaf.__init__: __init__ method from base class 'Component' is not called
Run Code Online (Sandbox Code Playgroud)

但在我的叶子中我不能要求:

def __init__(self, *args, **kw):
    Component.__init__(self, *args, **kw)
    self.dict = {}
Run Code Online (Sandbox Code Playgroud)

没有引发异常。

我必须忽略 pylint 警告还是存在一些错误的编码?

Ant*_*sma 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)
Run Code Online (Sandbox Code Playgroud)

  • @DrFalk3n。我们不要迷恋该模式的 Java 版本。Java 人喜欢他们的抽象类。Python 根本没有这个。我们都是成年人,我们都知道抽象类不起作用。省略引发 NotImplemented 的抽象 __init__ 确实没问题。您不必在 Python 中重复 Java/C++ 的愚蠢之处。 (4认同)