Python ABC 似乎允许不完整的实现

标签 python abstract-class abc

我正在尝试创建基类并强制所有子类实现它的接口(interface)。我正在使用 abc 模块来实现此目的。

这是基类:

class PluginBase:
    __metaclass = abc.ABCMeta
    @abc.abstractmethod
    def strrep(self):
            return
    @abc.abstractmethod
    def idle(self):
            print 'PluginBase: doing nothing here'
            pass
    @abc.abstractmethod
    def say(self, word):
            print 'PluginBase: saying a word ''', word, '\''
            return

这是 child :

class ConcretePlugin(PluginBase):
    def __init__(self, val):
            print 'initialising ConcretePlugin with value of %d' % val
            self.val = val
    def strrep(self):
            print 'ConcretePlugin = %d' % self.val
            return
    #'idle' method implementation is missing
    def say(self): # missing argument here; saying our own word =)
            print 'ConcretePlugin: this is my word'
            return

本次测试:

child = ConcretePlugin(307)
child.strrep()
child.idle()
child.say()

产生以下结果:

initialising ConcretePlugin with value of 307
ConcretePlugin = 307
PluginBase: doing nothing here
ConcretePlugin: this is my word

不要提示实现不完整!

所以我的问题是抽象基类是否不是真正抽象的。如果不是,那么有什么方法可以实现健壮的打字吗?

注意:我已将示例类命名为 PluginBaseCompletePlugin 以表明我需要确保客户端类实现正确的接口(interface).

我尝试从 object 派生 PluginBase,但这没有什么区别。 我正在使用 Python 2.7.1

任何帮助将不胜感激。

最佳答案

__metaclass更改为__metaclass__。否则它只是一个普通的隐藏属性。

>>> ConcretePlugin(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class ConcretePlugin with abstract methods idle

关于Python ABC 似乎允许不完整的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10749825/

相关文章:

c++ - 为什么我可以取消引用指向抽象类的指针?

Python:subprocess.call() 的当前工作目录在内存中的目录

python - 是否可以使用 Pulumi 创建 Azure 服务主体?

python - 使用日期时间每小时频率创建数据框

继承抽象类并实现接口(interface)的 C# 窗体。

python - 定义@property

python - 棘手的 : 'dict' object is not callable

java - 如何在Spring-MVC方法中绑定(bind)抽象类的子类?

python - 继承setter,覆盖python抽象类中的getter

python - 为什么在 Python 中使用抽象基类?