当 base 是抽象的时调用 base class ctor 时出现 pylint 错误

pylint error on calling base class ctor when base is abstract

有些情况 classes 应该 调用它们的超级 class 的构造函数,就像那些从抽象 classes 继承的:

class Father:
    def __init__(self):
        pass
class Son(Father):
    def __init__(self):
        self.salary = 700
    def __repr__(self):
        return f"my salary is {self.salary}"
print(Son())

不过,我的遗留代码包含一个对此有抱怨的 linter:

$ pylint3 --disable=too-few-public-methods,missing-docstring main.py 
No config file found, using default configuration
************* Module main
W:  5, 4: __init__ method from base class 'Father' is not called (super-init-not-called)

有没有办法将这个事实传达给pylint?

如果 Father class 是抽象的,你不应该有一个 __init__ (好吧,除非 init 做某事然后你应该调用它)并且你可以明确地让它继承来自 ABC 这样的:

import abc


class Father(abc.ABC):

    @abc.abstractmethod
    def interface(self):
        ...


class Son(Father):
    def __init__(self):
        self.salary = 700

    def __repr__(self):
        return f"my salary is {self.salary}"

    def interface(self):
        print(repr(self))


class BadSon(Father):
    """interface not implemented here"""


print(Son())
print(BadSon())

pylint 了解发生了什么:

a.py:26:6: E0110: Abstract class 'BadSon' with abstract
methods instantiated (abstract-class-instantiated)

但是当您使用 python 启动时也会出现错误:

my salary is 700
Traceback (most recent call last):
  File "b.py", line 26, in <module>
    print(BadSon())
TypeError: Can't instantiate abstract class BadSon with abstract methods interface

the documentation for the abc module