Why does the class object with option="first" appear in the list btest and the list ctest?
I have this problem with a larger piece of code so I wrote this smaller piece to understand better how this if/else statements work in a for-loop with list of class objects. But I still don't understand it.
class test:
def __init__(self,option,place):
self.option=option
self.place=place
def __repr__(self):
return("option:"+self.option+"\npalce:"+self.place)
optionlist=["first","second","thrid","fourth"]
placelist=["switzerland","germany","thailand","italy"]
testlist=[]
item=0
while item <len(optionlist):
testl=test(optionlist[item],placelist[item])
testlist.append(testl)
item+=1
btest=[]
ctest=[]
for x in testlist:
if x.option=="first":
btest.append(x)
print("here")
if x.option=="second":
print("here2")
# If I delete this 2nd if statement the ctest list
# doesn't contain a object with option="first", but if I
# leave it it does. Why?
else:
ctest.append(x)
print("no")
print("btest:",btest)
print("ctest:",ctest)
If I let this code run *without the 2nd if statement it gives me the following output:
here
no
no
no
btest: [option:first
palce:switzerland]
ctest: [option:second
palce:germany, option:thrid
palce:thailand, option:fourth
palce:italy]
Well that's also what I would expect, but why does it give the following output if I let it run *with the 2nd if statement:
here
no
here2
no
no
btest: [option:first
palce:switzerland]
ctest: [option:first
palce:switzerland, option:thrid
palce:thailand, option:fourth
palce:italy]
Aucun commentaire:
Enregistrer un commentaire