如何在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??

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

西尔夫兹

更新abc.abstractproperty在Python 3.3中已弃用。使用property具有abc.abstractmethod代替如图所示这里

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章