Python loop seems not to be iterating
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...
class stateClass: state = 0
Here you're creating a class level attribute - ie, state is shared by all instances of stateClass.
You're appending to your list stateClass itself - ie, the definition of the class, not an actual instance of a class...
As soon as you change state in one of them, all instances of stateClass now have that changed value.
You most likely want to be creating instances:
class State(object): def __init__(self, number): self.state = number Hawaii = State(50) Kentucky = State(23) # (making state numbers up here...) my_states =  my_states.append(Hawaii) my_states.append(Kentucky)
To then show state, do something like:
If you wanted a property so it avoids explicit setting from outside the class then:
class State(object): def __init__(self, number): self._state = number @property def state(self): return self._state