Get overridden functions of subclass
You can access the parent classes with cls.__bases__
, find all attributes of the parents with dir
, and access all the attributes of the class itself with vars
:
def get_overridden_methods(cls):
# collect all attributes inherited from parent classes
parent_attrs = set()
for base in cls.__bases__:
parent_attrs.update(dir(base))
# find all methods implemented in the class itself
methods = {name for name, thing in vars(cls).items() if callable(thing)}
# return the intersection of both
return parent_attrs.intersection(methods)
>>> get_overridden_methods(B)
{'a2'}
You can make use of the __mro__
tuple, which holds the method resolution order.
For your example:
>>> B.__mro__
( <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
So you could loop over that tuple and check if a B
method is also in one of the other classes.