我正在尝试创建基类并强制所有子类实现它的接口(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
不要提示实现不完整!
所以我的问题是抽象基类是否不是真正抽象的。如果不是,那么有什么方法可以实现健壮的打字吗?
注意:我已将示例类命名为 PluginBase
和 CompletePlugin
以表明我需要确保客户端类实现正确的接口(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/