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?

Answers


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:

print Hawaii.state

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

Need Your Help

How to properly dispose objects created for Ldap search using ADODB ADsDSObject provider

c# ldap disposal

I am looking for the best way how to lookup LDAP directory for users by given criteria. At the moment the best performance seems to offer usage of ADsDSObject provider. The code will run in ASP.NET...

Wildcard Type inference with abstract class

interface f# abstract-class type-inference

In the process of improving my F#, I have been experimenting with type inference and generics

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.