I would like to know if it is possible to use multiple inheritance with abstract base class in python. It seems like it should be possible but can't find a statement one way or the other.
The basic ABC example:
from abc import ABC, abstractmethod
class BaseABC(ABC):
@abstractmethod
def hello(self):
pass
class Child(BaseABC):
pass
child = Child()
This will fail due to "hello" not being implemented in "Child".
What I would like is to know how to combine ABC with multiple inheritance. I would like to make either the "BaseABC" or "Child" to inherit also from some other separate class. Explicitly:
from abc import ABC, abstractmethod
class BaseABC(ABC, dict):
@abstractmethod
def hello(self):
pass
class Child(BaseABC):
pass
child = Child()
This does not fail in the way expected as the first case does. Also:
from abc import ABC, abstractmethod
class BaseABC(ABC):
@abstractmethod
def hello(self):
pass
class Child(BaseABC, dict):
pass
child = Child()
This does not fail either. How can I require "Child" to implement "hello"?
The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes. 'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator.
abc. abstractmethod(function) A decorator indicating abstract methods. Using this decorator requires that the class's metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden.
ABCMeta . i.e abc. ABC implicitly defines the metaclass for us. The only difference is that in the former case you need a simple inheritance and in the latter you need to specify the metaclass.
Abstract Properties Properties are Pythonic ways of using getters and setters. The abc module has a @abstractproperty decorator to use abstract properties. Just like abstract methods, we need to define abstract properties in implementation classes, otherwise, Python will raise the error.
The issue is with inheriting from a dict, which is probably better explained by these guys:
So depending on little what you want to do with your subclassed dict you could go with MutableMapping as suggested in https://stackoverflow.com/a/3387975/14536215 or with UserDict (which is a subclass of MutableMapping) such as:
from abc import ABC, abstractmethod
from collections import UserDict
class BaseABC(ABC):
@abstractmethod
def hello(self):
pass
class Child(BaseABC, UserDict):
pass
child = Child()
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