Home > other >  Why is the class variable of parent class changed after creating an instance of child
Why is the class variable of parent class changed after creating an instance of child

Time:09-19

This is actually my first question on Stack Overflow, because for the first time I couldn't find a post about it (or I searched wrong). While I have a couple of years experience in the field of programming, I just recently started to use Python 3.x. Here I ran into the following problem.

I have two subclasses inheriting from the same parent. Depending on the subclass, a class variable of the parent class is changed. However, when creating first an instance of one subclass and after that an instance of the other one, the parent class variable is different. I was not expecting this, because I would expect that with creating a new instance of the parent class, the class variable would be the default value. Please refer to this code block:


class Parent:
    list1 = ['Parent_A', 'Parent_B']

    def __init__(self):
        #DO A LOF OF STUFF
        pass

    def get_list1(self):
        return self.list1

class Child1(Parent):
    list2 = ['Child1_A', 'Child1_B']

    def __init__(self):
        super(Child1, self).__init__()
        super(Child1, self).list1.extend(self.list2)


class Child2(Parent):
    list3 = ['Child2_A', 'Child2_B']

    def __init__(self):
        super(Child2, self).__init__()
        super(Child2, self).list1.extend(self.list3)

if __name__ == '__main__':
    inst_child1 = Child1()
    print(inst_child1.get_list())
    # Correct, expected: ['Parent_A', 'Parent_B', 'Child1_A', 'Child1_B']

    inst_child2 = Child2()
    print(inst_child2.get_list())
    # Incorrect, expected: ['Parent_A', 'Parent_B', 'Child2_A', 'Child2_B'] 
    # but got ['Parent_A', 'Parent_B', 'Child1_A', 'Child1_B', 'Child2_A', 'Child2_B']

Probably I don't understand (yet) the inheritance rules of Python, resulting in this problem. I apologize for this. Maybe one of you can explain this to me and maybe suggest improvements to this approach.

I would be really grateful for your help. Thanks in advance!

regards, Jan

CodePudding user response:

This is not my answer, but I'm not allowed to write comments.

difference between variables inside and outside of __init__() (class and instance attributes)

  • Related