【问题标题】:Pylint warnings on inherited nested class members继承嵌套类成员的 Pylint 警告
【发布时间】:2014-10-04 09:46:59
【问题描述】:

我们将一些特定功能实现为 Python 类,以便我们的开发人员继承它来轻松扩展。每个类都有一个带有项目列表的内部 Config 类。基类有一个空的 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 警告而不禁用它们? ¿有没有更好的方法来实现我想要的?注意,在实际程序中,config值是根据用户数据变化的,并不是一堆常量。

非常感谢。

【问题讨论】:

  • 没有回答你的问题,但这似乎是一种继承配置的复杂方式。
  • 我想避免编程错误,因此访问这些值是使用具体名称而不是随机字符串来完成的。这就是我这样做的原因。 Config 也有一些相关的功能。我在这里写了 Config 继承对象,但是在我的代码中它继承自 Config 对象并带有一些方法。

标签: python inheritance subclass inner-classes pylint


【解决方案1】:

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

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'

【讨论】:

  • 我想避免编程错误,因此访问这些值是使用具体名称而不是随机字符串来完成的。这就是我这样做的原因。 Config 也有一些相关的功能。我在这里写了 Config 继承对象,但是在我的代码中它继承自 Config 对象并带有一些方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-19
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
相关资源
最近更新 更多