【问题标题】:Pylint: Method could be a function in base classPylint:方法可能是基类中的函数
【发布时间】:2021-08-21 03:36:16
【问题描述】:

我想知道处理 Pylint 错误的最佳方法是抱怨以下示例中的情况:

class Base:
    def some_funct(self) -> List:
        """
        Intended to be overwritten in child classes, but
        if not, it's ok to return an empty list
        """
        return []

class Child1(Base):
     def some_funct(self) -> List:
          # Now, this does actual stuff!!
          return [a for a in self.some_iterable]

class Child2(Base):
   # An empty list is fine for this one
   pass

Pylint 会说 Base.safe_implementation 可能是一个函数(这是真的,但我希望 self 留在那里)

是否有更好的解决方案将其标记为pylint: disable?哪... .

这适用于 Python 3.6,以防相关。

【问题讨论】:

  • 为什么一开始就只有一个方法的类?
  • 如果Base实际上更复杂,那么pylint可以忽略。
  • @chepner:是的,确实如此。它被简化为示例。我将编辑问题并澄清它。
  • 我只会使用禁用注释(尽管专门用于忽略此特定错误/警告)。
  • 如果 pylint 的唯一问题是未使用 self,您可以构造一个列表推导来生成一个空列表,例如 [x for x in self.some_iterable if False]。 (这可能表明定义使用[x for self.some_iterable if self._predicate(x)] 的方法,子类只是覆盖self._predicate 而不是some_funct 本身。)

标签: python inheritance methods pylint


【解决方案1】:

将方法声明为staticmethod 以使pylint 开心:

class Base:
    @staticmethod
    def some_funct() -> List:
        """
        Intended to be overwritten in child classes, but
        if not, it's ok to return an empty list
        """
        return []

由于self 参数在正常情况下是隐式传递的,因此它不是方法外部签名的一部分。这允许在基类中将方法定义为staticmethod,并且仍然用派生类中的常规方法替换它,而不会改变外部行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2012-03-24
    • 2017-01-08
    相关资源
    最近更新 更多