[Tutor] Another question on global variables...

Sean 'Shaleh' Perry shalehperry@attbi.com
Wed, 16 Oct 2002 23:28:10 -0700


On Wednesday 16 October 2002 20:01, andy surany wrote:
> I know that nobody likes 'em.... but,
>
> If I define a global variable at the beginning of my program, like:
>
>     global abc
>     abc=3D[]
>
> Then assign it like:
>
> Class numberone:
>
>     def set_it:
>
>         abc=3D['1','2']
>         # This assignment works fine and the variable is used throughou=
t
> the class.
>
> Then reference it like:
>
> Class numbertwo:
>
>     def ref_it
>
>         size=3Dlen(abc)
>         # Here, it appears that abc is [] so the length is zero. Should=
 be
> 2
>
> Why doesn't this work? Are global assignments unique to the class which
> made the assignment? Or more specifically, do I need to reference a glo=
bal
> based on class, such as numberone.abc?? (or???)
>

class numberone does not assign to the global abc it assigns to a local=20
variable called abc.  As someone else mentioned on the first thread to AS=
SIGN=20
to a global you need to declare it global in the namespace where you do t=
he=20
assignment.  Observe:

global_text =3D "My name" # I am global

def foo(new_text):
    global_text =3D new_text

def bar(new_text):
    global global_text
    global_text =3D new_text

print global_text
foo("Hello, World!")
print global_text
bar("Hello, World!")
print global_text

The output will be:

My name
My name
Hello, World!