0

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

Jan
  • 3
  • 1
  • There is only one copy of a class variable per class. Any changes made will be visible wherever you refer to that particular class. – matszwecja Sep 19 '22 at 13:42
  • 1
    There is only one `Parent.list1`; you're extending it in place, so every instance of every child class sees the same value. You'd get the same issue even if you had only one child class, and created multiple instances of it. Normally, you wouldn't modify a class attribute in an `__init__()` method, you'd create an instance attribute. – jasonharper Sep 19 '22 at 13:42
  • So, I was looking at it in a wrong way by mixing up class and instance attributes. If I understand correctly, the class attribute will be stored in one part of memory and "permanently" overwritten until the application is terminated. Thank you both for clarifying this. Feels like a rooky mistake :-) – Jan Sep 19 '22 at 14:45

0 Answers0