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 警告还是存在一些错误的编码?
抽象初始化器是一个坏主意。您的代码可能会演变,以便您想要在根组件中进行一些初始化。即使您不知道为什么需要实现初始化程序。对于某些子类,空的初始值设定项是可以接受的选择。
如果您不需要 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)
| 归档时间: |
|
| 查看次数: |
2115 次 |
| 最近记录: |