[Tutor] help on scope
ak@silmarill.org
ak@silmarill.org
Sun, 22 Jul 2001 14:37:50 -0400
On Sun, Jul 22, 2001 at 07:33:50PM +0200, Charlie Clark wrote:
> Consider this:
>
> count = 0
>
> def func(something):
> print count
> count += 1
>
> This will print 0 but generate an error about the assignment. I know this is
> a scope problem but my brain is having trouble with accepting the fact that
> although I can access a variable I can't reference it. Do I have to use
> global to get around this? How does global actually work?
You can reference it, you just can't change it. Think of it as a safety
mechanism, because, well, it is :-).
>
> def func(something):
> global count
> print count
> count += 1
That's the accepted way of changing it.. Also, you can do this:
class my_class: pass
inst = my_class() # inst means 'instance', as in, "this classes' instance"
inst.count = 0
inst.count += 1
def func(something):
print inst.count
inst.count += 1
I personally use globals very rarely, 5 or so at most in a medium sized
program. Using instance members somehow 'feels' cleaner.
>
> Thanx for any help.
>
> Charlie
> --
> Charlie Clark
> Helmholtzstr. 20
> D?sseldorf
> D- 40215
> Tel: +49-211-938-5360
> GSM: +49-178-463-6199
> http://www.begeistert.org
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: http://silmarill.org/cymbaline