So, I am trying to define an abstract base class with couple of variables which I want to to make it mandatory to have for any class which "inherits" this base class.. So, something like:
class AbstractBaseClass(object):
foo = NotImplemented
bar = NotImplemented
Now,
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'
This should throw error:
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??
I maybe using the wrong terminology.. but basically, I want every developer who is "implementing" the above class to force to define these variables??
Update : abc.abstractproperty
has been deprecated in Python 3.3. Use property
with abc.abstractmethod
instead as shown 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
class AbstractBaseClass(object):
def __init__(self):
assert hasattr(self, 'foo')
assert hasattr(self, 'bar')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.