Why does appending to a list attribute of an object, modify the attribute of all the objects under the same class?

时间:2019-04-17 01:34:27

标签: python python-3.x class

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.

0 个答案:

没有答案