pythonabc似乎允许不完整的实现

2024-06-24 13:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建基类并强制所有子类实现它的接口。为此,我使用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

这是孩子:

^{pr2}$

此测试:

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

不要抱怨执行不彻底!在

所以我的问题是抽象基类是否真的是抽象的。如果不是这样的话,那么有什么方法可以使健壮的类型化?在

注意:我命名了示例类PluginBase和{},以表明我需要确保客户机类实现正确的接口。在

我尝试过从object派生PluginBase,但这没有什么区别。 我使用的是python2.7.1

任何帮助都将不胜感激。在


Tags: selfchildreturndef基类wordabcprint
1条回答
网友
1楼 · 发布于 2024-06-24 13:16:58

__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

相关问题 更多 >