stupid simple scope issue

JohnD john at nowhere.com
Sun Aug 4 14:20:27 EDT 2013


After 5 year of no Python programming I decided that I needed to brush
up my skills. Started writing on a reasonably complicated problem.
Unfortunately my basic Python skill are gone.

I present the bare-bore problem. This code does not produce the expected
result: can anyone tell me why? As you will guess, I want the first
three lines of output identical to the second three lines...

Can anyone point out the solution? Thanks!

#~/usr/bin/python
import random
class boys:
    state={}
class boy:
    state={
        'name':'',
        'age':''
        }
names=['a','b','c']

def add_names():
    global boys
    for n in names:
        boy.state['name']=n
        boy.state['age']=random.randint(1, 1000)
        boys.state[n]=boy.state
        print boy.state['name'], boy.state['age']

add_names()

for n in boys.state:
    boy.state=boys.state[n]
    print boy.state['name'], boy.state['age']





More information about the Python-list mailing list