How can I find all the abstract base classes that a given class is a "virtual subclass" of?
In other words, I'm looking for a magic function virtual_base_classes()
that does something like this:
>>> for cls in virtual_base_classes(list):
>>> print(cls)
<class 'collections.abc.MutableSequence'>
<class 'collections.abc.Sequence'>
<class 'collections.abc.Sized'>
<class 'collections.abc.Iterable'>
<class 'collections.abc.Container'>
(I don't know all the abc
classes that list
is registered with, so the above example may not be complete.)
Note that not every abstract base class will be defined in collections.abc
. There is a module abc
(distinct from collections.abc
) which provides the metaclass ABCMeta
. Any class that is an instance of ABCMeta
supports registration of "virtual subclasses" using the standard interface (the register
method). There's nothing that stops someone (whether a programmer or Python library) from creating an instance of ABCMeta
that does not belong in collections.abc
.
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier ( = 0 ) in the declaration of a virtual member function in the class declaration.
abstractmethod. 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.
3.3. 1 Abstract Base Classes. An ABC is a class that contains one or more pure virtual member functions. Such a class is not concrete and cannot be instantiated using the new operator. Instead, it is used as a base class where derived classes provide the implementations of the pure virtual methods.
Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class. The rule is every abstract class must use ABCMeta metaclass.
Use issubclass
and a list comprehension:
>>> import collections.abc
>>> import inspect
>>> [v for k, v in vars(collections.abc).items()
if inspect.isclass(v) and issubclass(list, v) ]
[<class 'collections.abc.Container'>,
<class 'collections.abc.Sequence'>,
<class 'collections.abc.MutableSequence'>,
<class 'collections.abc.Iterable'>,
<class 'collections.abc.Sized'>
]
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