Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend a list from a parent class?

I have the following code. The parent class has a list of items, which the children need to add to.

Every instance of parent needs to have this list, and every child needs to have that list + the extra values.

class Parent(object):
    a_list = ['parent_item1', 'parent_item2', ]

    def print_list(self):
        print(self.a_list)


class Child1(Parent):
    def __init__(self, *args, **kwargs):
        super(Child1, self).__init__(*args, **kwargs)
        self.a_list += ['child1_item']


class Child2(Parent):
    def __init__(self, *args, **kwargs):
        super(Child2, self).__init__(*args, **kwargs)
        self.a_list += ['child2_item']


parent = Parent()
child1 = Child1()
child2 = Child2()

parent.print_list()
    # >> ['parent_item1', 'parent_item2', 'child1_item', 'child2_item']
child1.print_list()
    # >> ['parent_item1', 'parent_item2', 'child1_item', 'child2_item']
child2.print_list()
    # >> ['parent_item1', 'parent_item2', 'child1_item', 'child2_item']

How can I get the following result instead?

['parent_item1', 'parent_item2', ]
['parent_item1', 'parent_item2', 'child1_item', ]
['parent_item1', 'parent_item2', 'child2_item', ]
like image 293
Joost VanDorp Avatar asked Oct 22 '25 04:10

Joost VanDorp


1 Answers

list += other_list extend the list in-place. Use + operator which returns a new list:

class Parent(object):
    a_list = ['parent_item1', 'parent_item2', ]
    def print_list(self):
        print(self.a_list)

class Child1(Parent):
    def __init__(self, *args, **kwargs):
        super(Child1, self).__init__(*args, **kwargs)
        self.a_list = self.a_list + ['child1_item']  # <-------

class Child2(Parent):
    def __init__(self, *args, **kwargs):
        super(Child2, self).__init__(*args, **kwargs)
        self.a_list = self.a_list + ['child2_item']  # <-------


parent = Parent()
child1 = Child1()
child2 = Child2()
parent.print_list()
child1.print_list()
child2.print_list()

output:

['parent_item1', 'parent_item2']
['parent_item1', 'parent_item2', 'child1_item']
['parent_item1', 'parent_item2', 'child2_item']

Alternatively, you can make a copy of the parent class' list:

...
self.a_list = self.a_list[:]
self.a_list += ['child1_item']
like image 127
falsetru Avatar answered Oct 24 '25 17:10

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!