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]
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]
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
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.