The below code is not acting as expected for me.
class stateClass:
state = 0
states = []
states.append(stateClass)
states.append(stateClass)
def populateStates(states):
for s in states:
if s.state == 0
print 'populating'
s.state = 1
populateStates(states)
the output is
states array length: 2
populating
this is failing the second time
for s in states:
if s.state == 0
if conditional is failing the second time although it is a different index in the array and thus the s.state should have been initialized to 0. So I think the loop is not iterating properly.
Anyone know whats wrong?
You don’t need the
;‘s – this isn’t C and co. etc…Here you’re creating a
class level attribute– ie,stateis shared by all instances ofstateClass.You’re appending to your list
stateClassitself – ie, the definition of the class, not an actual instance of a class…As soon as you change
statein one of them, all instances ofstateClassnow have that changed value.You most likely want to be creating instances:
To then show state, do something like:
If you wanted a
propertyso it avoids explicit setting from outside the class then: