name space problem
marek.rocki at wp.pl
marek.rocki at wp.pl
Tue Oct 23 19:20:25 EDT 2007
BBands napisa (a):
> An example:
>
> class classA:
> def __init__(self):
> self.b = 1
>
> def doStuff():
> some calcs
> a..b = 0
>
> a = classA():
> print a.b
> doStuff()
> print a.b
>
> That works as hoped, printing 1, 0.
>
> But, if I move doStuff to another module and:
>
> import doStuff
>
> class classA:
> def __init__(self):
> self.b = 1
>
> a = classA()
> print a.b
> doStuff.doStuff()
> print a.b
>
> I get a 1 printed and an error: NameError: global name 'a' is not
> defined
>
> I think this is a name space issue, but I can't grok it.
>
> Thanks in advance,
>
> jab
Hello. Indeed the doStuff function in the doStuff module can't do 'a.b
= 0' (the double dot was just a typo, right?) because it doesn't know
anything about an object named a.
I think the right solution would be not to use 'a' as a global
variable, but rather to pass it as an explicit parameter to the
function.
In module doStuff:
def doStuff(a):
# some calcs
a.b = 0
In the main module:
import doStuff
# ...
doStuff.doStuff(a)
More information about the Python-list
mailing list