如何在python中定义一个抽象类并强制实现变量

时间:2015-05-12 20:49:14

标签: python

所以,我试图定义一个带有几个变量的抽象基类,我想让它对于“继承”这个基类的任何类都是强制性的。所以,像:

class AbstractBaseClass(object):
   foo = NotImplemented
   bar = NotImplemented

现在,

class ConcreteClass(AbstractBaseClass):
    # here I want the developer to force create the class variables foo and bar:
    def __init__(self...):
        self.foo = 'foo'
        self.bar = 'bar'

这会引发错误:

class ConcreteClass(AbstractBaseClass):
    # here I want the developer to force create the class variables foo and bar:
    def __init__(self...):
        self.foo = 'foo'
        #error because bar is missing??

我可能使用了错误的术语..但基本上,我希望每个“实现”上述类的开发人员强制定义这些变量?

2 个答案:

答案 0 :(得分:5)

更新:Python 3.3中已弃用abc.abstractproperty。将propertyabc.abstractmethod一起使用,而不是here

import abc

class AbstractBaseClass(object):

    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def foo(self):
        pass

    @abc.abstractproperty
    def bar(self):
        pass

class ConcreteClass(AbstractBaseClass):

    def __init__(self, foo, bar):
        self._foo = foo
        self._bar = bar

    @property
    def foo(self):
        return self._foo

    @foo.setter
    def foo(self, value):
        self._foo = value

    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, value):
        self._bar = value

答案 1 :(得分:1)

class AbstractBaseClass(object):
    def __init__(self):
        assert hasattr(self, 'foo')
        assert hasattr(self, 'bar')