I have a base class with a lot of __init__
arguments:
class BaseClass(object): def __init__(self, a, b, c, d, e, f, ...): self._a=a+b self._b=b if b else a ...
All the inheriting classes should run __init__
method of the base class.
I can write a __init__()
method in each of the inheriting classes that would call the superclass __init__
, but that would be a serious code duplication:
class A(BaseClass): def __init__(self, a, b, c, d, e, f, ...): super(A, self).__init__(a, b, c, d, e, f, ...) class B(BaseClass): def __init__(self, a, b, c, d, e, f, ...): super(A, self).__init__(a, b, c, d, e, f, ...) class C(BaseClass): def __init__(self, a, b, c, d, e, f, ...): super(A, self).__init__(a, b, c, d, e, f, ...) ...
What's the most Pythonic way to automatically call the superclass __init__
?
The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.
The Python super() method lets you access methods in a parent class. You can think of super() as a way to jump up to view the methods in the class from which another class is inherited. The super() method does not accept any arguments. You specify the method you want to inherit after the super() method.
If, as is common, SubClass actually does want to have all of BaseClass 's invariants set up before it goes on to do its own customisation, then yes you can just call BaseClass. __init__() (or use super , but that's complicated and has its own problems sometimes). But you don't have to.
The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.
super(SubClass, self).__init__(...)
Consider using *args and **kw if it helps solving your variable nightmare.
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