python - 关于继承的嵌套类成员的 Pylint 警告

标签 python inheritance subclass inner-classes pylint

我们将一些特定功能实现为 Python 类,以便继承它的开发人员轻松扩展。每个类都有一个带有项目列表的内部配置类。基类有一个空的Config类,每个继承类都定义了一些项目到里面。然后每次使用 Config 子类的项时 pylint 都会报错。​​

例如,这段代码:

class A(object):

  class Config(object):

    def __init__(self):
      self.item1 = 1
      self.item2 = 2

  def __init__(self):
    self._config = self.Config()


class B(A):

  class Config(A.Config):

    def __init__(self):
      super(B.Config, self).__init__()
      self.item3 = 3
      self.item4 = 4

  def do_something(self):
    if self._config.item3 == 3:
      print 'hello'
    if self._config.item1 == 5:
      print 'bye'

然后您可以将其用作:

>>> B().do_something()
hello

我们的程序运行良好,背后的想法相同。每次我们使用这些元素时,pylint 都会继续提示。例如,在这种情况下它会说:

E1101(no-member) Instance of 'Config' has no 'item3' member

所以我的问题是,如何在不禁用这些 pylint 警告的情况下避免它们? ¿有没有更好的方法来实现我想要的?请注意,在实际程序中,配置值会根据用户数据而变化,而不是一堆常量。

非常感谢。

最佳答案

这似乎过于复杂的 IMO。使用字典进行配置会做得很好。例如:

class A(object):

  def __init__(self):
    self._config = {
        'item1': 1,
        'item2': 2,
    }


class B(A):

  def __init__(self):
      super(B, self).__init__()
      self._config.update({
          'item3': 3,
          'item4': 4,
      })

  def do_something(self):
    if self._config['item3'] == 3:
      print 'hello'
    if self._config['item1'] == 5:
      print 'bye'

关于python - 关于继承的嵌套类成员的 Pylint 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25245414/

相关文章:

java - 具有不同参数列表的继承

inheritance - 为什么将实例声明为父类(super class)型但将其实例化为子类型,加上里氏替换原则

ruby - 继承 Ruby Hash,对象没有 Hash 的方法?

python - Pandas 数据框中的自定义排序

python - 尝试通过选择特定数据在 Python 中创建 3D 矩阵

C# - 如何复制/创建对象作为后代

java - Java继承中 "override abstract methods"可以用 "implement abstract methods"代替吗?

java - 如何在 Rhino 中子类化内部(静态)类?

python - 按照字符串中的格式用日期时间填充 python 字符串

python - 将 blobstore blob 作为文件处理 (python)