Search code examples
pythoninheritanceinitializationsubclassing

What are the requirements to cause an initialization of the parent class in child class?


I am still new to OOP.

In an instance of a child class I want to use a parameter that is set when the parent class is initialized:

class parent():
    def __init__(self, config):
        self._config = config

class child(parent):  
    print self._config

x = "Hello"
c = child(x)

This does not work, an error is thrown since self is unknown. Do I really need to copy the complete __init__ block from the parent class every time? I saw that in some cases an initialization can be triggered without an __init__ block:

class parent():
    def __init__(self, config):
        self._config = config

class child(parent):  
    # Nonsense since not itarable, but no error anymore
    def next(self):
        print self._config

x = "Hello"
c = child(x)

Although that does not work, it still throws no error. Is there any short method to initialize the parent class in the child class or to get all parameters from the parent?


Solution

  • class parent:
        def __init__(self, config):
            self._config = config
    
    class child(parent):
    
        def __init__(self,config):
            parent.__init__(self,config)
    
        def next(self):
            print self._config
    
    x = child("test")
    x.next() # prints test
    

    All the parameters to be passed to parent must be passed to child to initialize the parent inside the __init__ of child