0

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?

3
  • Why the semicolons? This is python, not javascript. :-) Commented Sep 10, 2012 at 10:52
  • 1
    You are adding the class, not instances to the array. Do you really want this? Commented Sep 10, 2012 at 10:53
  • sorry im switching over, I do it without realising Commented Sep 10, 2012 at 10:53

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

How do I access the elements of the state then after initialisation? Hawaii.number isnt working for me?
5

Python is not Java. The loop is fine, the problem is the class.

state is a class variable, not an instance variable. It is shared by all instances of the class. And you're not actually instantiating the class at all.

Do this instead:

class stateClass(object):
  def __init__(self):  
    self.state = 0

states.append(stateClass())

And you don't need the semicolons.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.