1

I have a class who has a default list attribute. When object is created the list is often empty. There is also an object method to append items to this list. However, each time a task is added to this using self.list1.append("string"), all the objects under the same class are affected. Is there a reason for this?

I have tried adding a standalone function to do this, tried an instance method and also tried in the shell. I get the same results. The list1 attribute of all class objects are appended.

Is there something obvious I am missing?

"tasks" is the list which is an attribute of the class objects:

    def __init__(self,id,tasks=[]):
        self.id=id
        self.tasks=tasks
        print('Added')

The method

    def addt(self,task):   
        self.tasks.append(task)

Edit: To clarify this question is not about the behavior of (tasks=[]) default assignment, but the unexpected behavior of appendix the value to ALL the objects of the class. i.e a.addt seems to affect object b also which is unexpected.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
NVAR
  • 25
  • 7
  • @wim this is not a duplicate of the linked question (at least from my understanding they are not related). My question is reg. objects that are not modified by a method being affected by an instance method called on another object. – NVAR Apr 17 '19 at 02:29
  • You will have to make an MCVE then – wim Apr 17 '19 at 05:40

0 Answers0