Rom*_*ent 3 python abstract-class pep8 python-3.x visual-studio-code
我在 Visual Studio 代码中使用 pep8,我只是尝试编写一些抽象类。
问题是我收到错误,[pylint] E1101:Instance of 'MyAbstract' has no 'child_method' member因为 pep8 没有意识到该方法定义良好,但在子类中。
为了说明我的问题,这里有一个代码片段,为了清晰起见,该代码片段被缩减到最少:
class MyAbstract:
def some_method(self):
newinfo = self.child_method()
# use newinfo
class MyChild(MyAbstract):
def child_method(self):
# Do something in a way
class OtherChild(MyAbstract):
def child_method(self):
# Do the same thing in a different way
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
澄清
MyAbstract 类不应被实例化,并且子类将继承some_method. 这个想法是在子类实例上使用它。
如果你想MyAbstract成为一个带有抽象方法的抽象类child_method,Python有一种在模块中表达的方式abc:
import abc
class MyAbstract(metaclass=abc.ABCMeta):
@abc.abstractmethod
def child_method(self):
pass
def some_method(self):
newinfo = self.child_method()
do_whatever_with(newinfo)
Run Code Online (Sandbox Code Playgroud)
您的 linter 将不再抱怨不存在的方法,而且作为奖励,Python 将检测使用未实现的抽象方法实例化类的尝试。