1

基本クラスを作成し、すべてのサブクラスにそのインターフェイスを実装させようとしています。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

そして、これが子供です:

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

PluginBaseから派生しようとしましobjectたが、これは違いはありません。私はPython 2.7.1を使用しています

どんな助けでも大歓迎です。

4

1 に答える 1

2

に変更__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
于 2012-05-25T06:55:40.007 に答える