Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #51937

Re: stupid simple scope issue

References <51fe9b6b$0$1689$e4fe514c@dreader35.news.xs4all.nl>
Date 2013-08-04 19:39 +0100
Subject Re: stupid simple scope issue
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.190.1375641581.1251.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Aug 4, 2013 at 7:20 PM, JohnD <john@nowhere.com> wrote:
> #~/usr/bin/python

If this is meant to be a Unix-style shebang, the second character
needs to be ! not ~. This has no effect on Python though.

> import random
> class boys:
>     state={}
> class boy:
>     state={
>         'name':'',
>         'age':''
>         }

At no time do you actually instantiate any objects from these types.
In fact, you may as well drop the class blocks and the ".state" usage
and simply use:

boys = {}
boy = {'name':'', 'age':''}

as this will achieve the exact same thing.

> def add_names():
>     global boys

The global declaration is needed only if you assign to the name, eg
"boys = <...>" - it's superfluous here.

>     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']

Each time you do this, you're modifying the same 'boy' mapping, then
putting another reference to it in 'boys'. I think possibly what you
want here is to construct a new boy() instance for each one.

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

I'd look at doing it more like this:

class boy:
    def __init__(self,name,age):
        self.name=name; self.age=age
boys = {}

def add_name(n):
    b = boy(n,random.randint(1, 1000))
    boys[n] = b
    print b.name, b.age

for n in 'a','b','c':
    add_name(n)

for n,b in boys.items():
    print b.name, b.age


Or possibly even dispense with the boy class altogether and simply use
a dictionary - or simply map a name to an age, since (as you can see
in the final loop) it's easy enough to iterate over the dictionary.
(Note that the code above is untested and probably has an egregious
bug in it somewhere.)

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

stupid simple scope issue JohnD <john@nowhere.com> - 2013-08-04 18:20 +0000
  Re: stupid simple scope issue Chris Angelico <rosuav@gmail.com> - 2013-08-04 19:39 +0100
    Re: stupid simple scope issue JohnD <john@nowhere.com> - 2013-08-04 19:21 +0000
      Re: stupid simple scope issue Chris Angelico <rosuav@gmail.com> - 2013-08-04 21:03 +0100
        Re: stupid simple scope issue JohnD <john@nowhere.com> - 2013-08-05 07:21 +0000

csiph-web