stupid simple scope issue
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']
--
http://mail.python.org/mailman/listinfo/python-list
Re: stupid simple scope issue
On 2013-08-04, Chris Angelico wrote: [...] Thank you very much. The dust is slowly starting to move. The code posted is nothing like the real thing, but I tried to capture the essence. >From your commants I think I see my mistake. Thank you very much for your reply! -- http://mail.python.org/mailman/listinfo/python-list
Re: stupid simple scope issue
On 2013-08-04, Chris Angelico wrote: > On Sun, Aug 4, 2013 at 8:21 PM, JohnD wrote: >> On 2013-08-04, Chris Angelico wrote: [...] > > Python does have a slightly odd (compared to other languages) > interpretation of "variable assignments" (name bindings, really) > inside a class block. Trips up a lot of people. Changed the code: >10% smaller, more elegant, and it seems to work! If it really works I am close to half-way... -- http://mail.python.org/mailman/listinfo/python-list
