Skip to main content
 首页 » 编程设计

Python 复合模式异常处理和 pylint

2025年05月04日9zhengyun_ustc

我在 this way 中实现了一个复合模式:

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 

但是进入我的 Leaf 我不能调用:

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

没有引发异常。

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

请您参考如下方法:

抽象初始化器是个坏主意。您的代码可能会发生变化,因此您想在根组件中进行一些初始化。即使您不这样做,为什么也需要执行初始化程序。对于某些子类,空的初始值设定项是可以接受的选择。

如果您不想要 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)