2
class CoolList:

    def __init__(self, list=[]):
        self._list = list

    def append(self, item:str):
        self._list.append(item)


if __name__ == "__main__":
    a = CoolList()
    b = CoolList()
    a.append("test")
    print(a._list)
    print(b._list)
    # output: 
    # ['test']
    # ['test']

I have two objects of CoolList, a and b.

_list is not a static class member.

But when I append an item into a,

b also gets that item.

Why is that happening?

LinFelix
  • 1,026
  • 1
  • 13
  • 23
landings
  • 686
  • 1
  • 8
  • 25
  • 3
    Do not use mutables as default arguments: https://stackoverflow.com/questions/66905366/passing-a-list-as-an-argument-but-keeping-default-values Link to Python Docs for default args: https://docs.python.org/3/tutorial/controlflow.html#default-argument-values – ivvija Apr 28 '22 at 08:41

0 Answers0