我目前正在为 python 2 进行开发,我正在尝试使用抽象基类来模拟接口。我有一个接口、该接口的基本实现以及许多扩展基本实现的子类。看起来像这样:
class Interface(object):
__metaclass__ = ABCMeta
class IAudit(Interface):
@abstractproperty
def timestamp(self):
raise NotImplementedError()
@abstractproperty
def audit_type(self):
raise NotImplementedError()
class BaseAudit(IAudit):
def __init__(self, audit_type):
# init logic
pass
@property
def timestamp(self):
return self._timestamp
@property
def audit_type(self):
return self._audit_type
class ConcreteAudit(BaseAudit):
def __init__(self, audit_type):
# init logic
super(ConcreteAudit, self).__init__(audit_type)
pass
但是 PyCharm 通知我
ConcreteAudit
应该实现所有抽象方法。但是,BaseAudit
(未指定为 abc)已经实现了这些方法,并且 ConcreteAudit
是 BaseAudit
的子类。为什么 PyCharm 警告我?不是应该检测到IAudit
的合约已经通过BaseAudit
执行了吗?
PyCharm 为什么警告您?
因为所有 Python IDE 都很糟糕,这就是原因。
每当实习生/初级程序员/同事告诉我我写的东西对他不起作用时,我都会告诉他,在他通过从命令行或库存中执行 Python 脚本来尝试之前我不会讨论它口译员。 99% 的情况下,问题都会消失。
为什么它们很糟糕?打败我。但它们有时都会隐藏异常,有时可能会导入您不知道的东西,并且有时会决定(就像在本例中)某些问题是在普通解释器上运行的真实程序根本不会有的有问题。
我尝试使用 Python 2.7 和 Python 3.4 编写代码,只要我在顶部添加
from abc import ABCMeta, abstractproperty
,它就可以完美运行。
因此,只需放弃 PyCharm,或更新标签以显示错误所在。