Search code examples
python-3.xinheritanceparent-childsuper

Get superclass input parameter in child class python3


I need some help in understanding below problem in python3.6. I've 2 classes: parent & child. child inherits parent. I need to access the variables declared/passed in child within parent class.

But when i run the command :

Command: child(fmt='abc').test_func()

Observations:

  1. This returns 'X' which is the default value, but i'm expecting 'abc' to be returned. -- So the value passed is not working.
  2. If i return the variable self.mode within test_func, it returns me correct value. -- So the value declared is working.

Note: **kwargs is intended in child class because it needs to accept variable inputs at runtime, which works.

TIA

========================================================================

class parent:

def __init__(self, fmt = 'X'):
    self.fmt = fmt
    self.mode = 'abc'

========================================================================

class child(parent):

def __init__(self, **kwargs):
    super().__init__()   

def test_func(self):
    return self.fmt

========================================================================


Solution

  • Step1 -- hand the variable 'abc' to the child

    child(fmt='abc').test_func()
    
    # this works, the variables goes into the child's __init__ function
    

    Step2 -- the child should hand it up to parent

    def __init__(self, **kwargs):
        # the variable is here
        super().__init__()  
        # but never gets passed or assigned anywhere
    

    Step3 -- the parent assigns it

    def __init__(self, fmt = 'X'):
        # your input of 'abc' never reaches here
        self.fmt = fmt
    

    Two possible solutions. Either

    • [BEST] Delete the child's __init__ method, now the variable will pass directly to the parent's __init__ method skipping Step2 entirely.
    • Fix the child's __init__ method, by forwarding any supplied variables (so super().__init__(**kwargs))