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??
Practical Data Science using Python An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.
Abstract Class Requirements Therefore, we need to define an abstract class (not exactly) with the following requirements: the base class must not be instantiated. the base class has an abstract class variable (emphasis on class variable, which defines the schema for that model)
Abstract classes can have instance variables (these are inherited by child classes). Interfaces can't. Finally, a concrete class can only extend one class (abstract or otherwise). However, a concrete class can implement many interfaces.
We need to initialize the non-abstract methods and instance variables, therefore abstract classes have a constructor. Also, even if we don't provide any constructor the compiler will add default constructor in an abstract class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With