Re: 'local' var in module
From: Josiah Carlson (jcarlson_at_uci.edu)
Date: 10/07/04
- Next message: Robert Brewer: "RE: Converting a set of data to string and then into a file"
- Previous message: Mel Wilson: "Re: 'local' var in module"
- In reply to: Andreas Lobinger: "'local' var in module"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 07 Oct 2004 08:36:40 -0700 To: Andreas Lobinger <andreas.lobinger@netsurf.de>, python-list@python.org
> lobingera@sibyl: cat flip.py
> import random
>
> paras = { 'flength' : 22,
> 'cset' : 'abcdefghijkl' }
> rstate = 1
>
> def f():
> random.seed(rstate)
> s = list()
>
> for i in range(paras['flength']):
> s.append(random.choice(paras['cset']))
>
> return "".join(s)
When you are only reading things, Python will pull variables from the
local or global scope as necessary.
> def g():
> random.seed(rstate)
> s = list()
>
> for i in range(paras['flength']):
> s.append(random.choice(paras['cset']))
>
> rstate = random.getseed()
> return "".join(s)
If you try to write to a variable in a scope, Python believes that the
variable is local to this scope, so doesn't attempt to fetch it from
globals, and will only write to the local copy.
That is, unless you include the 'global' keyword. Add:
global rstate
to g() and watch everything work the way you expect.
- Josiah
- Next message: Robert Brewer: "RE: Converting a set of data to string and then into a file"
- Previous message: Mel Wilson: "Re: 'local' var in module"
- In reply to: Andreas Lobinger: "'local' var in module"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|