Search code examples
pythonclassinheritanceparentinstance-variables

How to pass all class variables from a parent *instance* to a child class?


Here's an example of what I'm trying to do:

class Parent():
    def __init__():
        self.parent_var = 'ABCD'
        x = Child(self)    # self would be passing this parent instance

class Child():
    def __init__(<some code to pass parent>):
        print(self.parent_var)

foo = Parent()

Now I know what you're thinking, why not just pass parent_var itself to the child instance? Well my actual implementation has over 20 class variables in Parent. I don't want to have to manually pass each variable to the __init__ of the Child instance that's instantiated in Parent-- is there a way to make all Parent class variables available to Child?

EDIT - SOLVED: This is the way I found that works:

class Parent():
    def __init__(self):
        self.parent_var = 'ABCD'  # but there are 20+ class vars in this class, not just one
        x = Child(self)           # pass this parent instance to child        

class Child():
    def __init__(self, parent):
        for key, val in vars(parent).items():
            setattr(self, key, val)

        print(self.parent_var)  # successfully prints ABCD


foo = Parent()


Solution

  • If you inherit from the parent class all variables will be present in child classes. Use super init in the child to make sure the parent class instantiates.

    class Parent:
        def __init__(self):
            self.parent_var = 'ABCD'
    
    class Child(Parent):
        def __init__(self):
            super().__init__()
    
    child = Child()
    print(child.parent_var)
    

    prints:

    'ABCD'