I've read many of the other questions and opinions about super
like super-harmful and super-considered-super but none of them mention inspect.getmro
as an alternative. I'm wondering, instead of implementing a class hierarchy like this:
class Base(object):
def __init__(self, **kwargs):
print("base init")
class A(Base):
def __init__(self, **kwargs):
super(A, self).__init__()
print("a init")
class B(Base):
def __init__(self, **kwargs):
super(B, self).__init__()
print("b init")
class C(A, B):
def __init__(self, **kwargs):
super(C, self).__init__()
print("c init")
Why don't we do something like this?
import inspect
class Base(object):
def __init__(self, **kwargs):
mro = inspect.getmro(self.__class__)
for mro_cls in reversed(mro):
if hasattr(mro_cls, "_init"):
mro_cls._init(self, **kwargs)
def _init(self, **kwargs):
print("base")
class A(Base):
def _init(self, **kwargs):
print("a init")
class B(Base):
def _init(self, **kwargs):
print("b init")
class C(A, B):
def _init(self, **kwargs):
print("c init")
It seems like there are some potential benefits:
- New developers can extend the hierarchy by implementing
_init
without additional boilerplate. - Enforce standard practices like initializing the parent class before the child for attribute overrides.
Are there any drawbacks that I'm missing?
source https://stackoverflow.com/questions/71132222/why-should-i-require-all-subclasses-to-call-super-if-i-can-use-getmro-to-do-it
Comments
Post a Comment