super(SubClass, self).__init__(...)
Consider using *args and **kw if it helps solving your variable nightmare.
Answer from user2665694 on Stack Overflowsuper(SubClass, self).__init__(...)
Consider using *args and **kw if it helps solving your variable nightmare.
You have to write it explicitly, but on the other hand, if you have lots of args, you should probably use *args for positional args and **kwargs for keyword args.
class SubClass(BaseClass):
def __init__(self, *args, **kwargs):
super(SubClass, self).__init__(*args, **kwargs)
# SubClass initialization code
Another technique you could use is to minimize the code in init and then at the end of init function, call another custom function. Then in the subclass, you just need to override the custom function
class BaseClass(object):
def __init__(self, *args, **kwargs):
# initialization code
self._a = kwargs.get('a')
...
# custom code for subclass to override
self.load()
def load():
pass
class SubClass(BaseClass)
def load():
# SubClass initialization code
...
How to handle inheritance so methods called in constructors dont overwrite between parent and child?
How do derived class constructors work in python? - Stack Overflow
inheritance - Calling a parent class constructor from a child class in python - Stack Overflow
pray: help me understand super, init, args and kwargs
Let's start with the easy to explain ones: variatic (*args) and keyword parameters (**kwargs). Both are special in that they allow for any number of arguments to be passed. Those arguments passed beyond the parameters specified by the invoked function (or method) will be collected in either *args or **kwargs, depending on how the arguments were passed. If the argument was passed as a keyword (keyword=some_argument), it will be added to the **kwargs dictionary, else the passed argument will be used to construct the *args tuple. How 'bout an example?
def foo(first_arg, *args, **kwargs):
"""The first parameter: 'first_arg' is required and will be
populated with the first passed argument ('first'). Any
additional unnamed arguments passed ('second' and
'third') will be contained by the '*args' parameter. Finally,
any keyword arguments (a_name='fourth',
another_name='fifth') will be contained in '**kwargs'.
"""
# Given the function call below: kwargs = {'a_name': 'fourth',
'another_name': 'fifth'}
for key, value in kwargs.items():
print("Key: {}, Value: {}".format(key, value))
# Given the function call below: args = ('second', 'third')
for arg in args:
print("Unnamed Argument: {}".format(arg))
foo('first', 'second', 'third', a_name='fourth', another_name='fifth')
It is worth noting that there is nothing special about the parameter names args or kwargs. They are not keywords and are not magic in any way. You could use *frank and **hamster if you like. But don't. Unless those make sense in the context of your function.
I'll get to the others shortly unless someone else beats me to it. Feel free to ask any followup questions.
Edit: Awkward names for named args changed. Also: formatting.
More on reddit.comVideos
I have this class that other modules will need to import and extend. I want the class to examine the parameters it is fed during construction time to fail early.
class Parent():
def __init__(self, a):
self.a = a
self.validate_constructor()
def validate_constructor():
if self.a <= 0
print(msg)
class Child(Parent):
def __init__(self, a, b, c):
super().__init__(a)
self.b = b
self.c = c
self.validate_constructor()
def validate_constructor():
if self.b <= 0:
print(msg)
if self.c <= 0:
print(msg)That makes sense to me, but apparently the validate_constructor in Parent is overwritten with Child’s validate_constructor, because that code will throw an issue for “no self.b” when I try to init a Child. I can always call the Parent’s validate from Parent by using ‘class.validate_constructor(self)’ but that looks horrible.
Does python call by default the base class constructor's when running the derived class' one? Do I have to implicitly do it inside the derived class constructor?
No and yes.
This is consistent with the way Python handles other overridden methods - you have to explicitly call any method from the base class that's been overridden if you want that functionality to be used in the inherited class.
Your constructor should look something like this:
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
NeuralNetworkBase.__init__(self, numberOfInputers, numberOfHiddenNeurons, numberOfOutputs)
self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))
self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))
Alternatively, you could use Python's super function to achieve the same thing, but you need to be careful when using it.
You will have to put this in the __init__() method of NeuralNetworkBackPropagation, that is to call the __init__() method of the parent class (NeuralNetworkBase):
NeuralNetworkBase.__init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs)
The constructor of the parent class is always called automatically unless you overwrite it in the child class. If you overwrite it in the child class and want to call the parent's class constructor as well, then you'll have to do it as I showed above.