0
class Demo:  
    def __init__(self,l=[]):  
        self.l=l  
    def add(self,x):  
        t=Demo()  
        t.l.append(x)  
        print(t.l)

o1=Demo()  
o2=Demo()  
o1.add(1)  
o2.add(2)  

output:

[1]  
[1,2]  
Jérôme
  • 13,328
  • 7
  • 56
  • 106

2 Answers2

0
class Demo:
    def __init__(self, l=[]):
        self.l = l[:]

    def add(self, x):
        t = Demo()
        t.l.append(x)
        print(t.l)


o1 = Demo()
o2 = Demo()
o1.add(1)
o2.add(2)

Lists in Python are a bit of a weird thing. The modification above allows you to work with a new list

Sam
  • 147
  • 11
0

This is the mutable default parameter pitfall.

def __init__(self,l=[]):

The empty list object is created at module level and common to all Demo instances.

See "Least Astonishment" and the Mutable Default Argument.

Jérôme
  • 13,328
  • 7
  • 56
  • 106