I'm new to python. When I code in Python I notice this strange behavior:
Class x:
class x:
x1 = 0
def __init__(self, x):
self.x1 = x
Class xcontainer:
class xContainer:
coint = []
def __init__(self, coint = []):
self.coint = coint
def add_x(self, x):
self.coint.append(x)
when I try to run this code:
def Main():
list_xcon = []
for i in range (0,2):
xcon = xContainer()
for j in range (i, i+1):
xcon.add_x(x(j))
list_xcon.append(xcon)
for xcont in list_xcon:
for xc in xcont.coint:
print xc.x1
I get those results:
0 1 0 1
but when I run this code:
def Main():
list_xcon = []
for i in range (0,2):
listt = []
xcon = xContainer(listt)
for j in range (i, i+1):
xcon.add_x(x(j))
list_xcon.append(xcon)
for xcont in list_xcon:
for xc in xcont.coint:
print xc.x1
I get those results:
0 1
Why is that? According to class xcontainer
, the default of coint
should be []
- empty list. So why sending empty list change the result?
By the way, I read that using coint = None
as default and checking if coint is None: coint = []
is better way, but it seems that it does not change the results here.
I will appreciate any explanation. I'm confused.
Thanks.