How to define an abstract class in python and enforce variables
So I'm trying to define an abstract base class with a couple of variables that I want to make mandatory for any class that "inherits" that 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 an 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??
Perhaps I am using the wrong terminology .. but basically, I want every developer to "implement" the above class to force these variables to be defined
+3
source to share
2 answers
Update : abc.abstractproperty
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
+5
source to share