python - How do I extend a list from a parent class? -


I have the following code: Parents have a list of items in the class, which children have to add.

For every example of parents this list should be, and every child needs that list + additional values.

  class generator (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'] Category Child2 (parent): def __init __ (self, * Args, ** kwargs): super (child2, self) .__ init__ (* args, ** kwargs) self.a_list + = ['child2_item'] parent = child (child1 = child1) child2 = child2 () Parent.print_list () # & gt; & Gt; ['Parent_itum 1', 'Parent_time 2', 'child1_item', 'child2_item'] child 1.print_list () # & gt; & Gt; ['Parent_itm1', 'Parent_itum2', 'Child1_item', 'Child2_item'] Child 2.print_list () # & gt; & Gt; ['Parent_item1', 'parent_item2', 'child1_item', 'child2_item']  

How do I achieve the following results instead? ['Parent_item1', 'parent_item2',] ['parent_item1', 'parent_item2', 'child1_item',] ['parent_item1', 'parent_item2', 'child2_item',]

list + = other_list increase list In- Use the + operator, which gives a new list:

  class guardian (object): a_list = ['parent_item1', 'parent_item2' ,] Df 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'] # & lt; ------- Class Child2 (parent): def __init __ (self, * args, ** kwargs): Super (Child2, self) .__ init __ (* args, ** kwargs) self .a_list = self .a_list + ['child2_item'] # & lt; ------- parent = parent () child1 = child1 () child2 = child2 () parent.print_list () child1.print_list () child2.print_list ()  

Product:

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

Alternatively, you can make a copy of the list of the original category:

  ... Self.a_list = self.a_list [:] self.a_list + = ['Child1_item']  

Comments

Popular posts from this blog

winforms - C# Form - Property Change -

javascript - amcharts makechart not working -

java - Algorithm negotiation fail SSH in Jenkins -