[Tutor] Why thus?

Patrick Phalen python-list@teleo.net
Sun, 12 Mar 2000 11:14:00 -0800


[Gerrit Holl, on Sun, 12 Mar 2000]
:: <quote name="Arthur Siegel" date="952860453" email="ajs@ix.netcom.com">
:: > Can't quite see what's happening here.
:: > 
:: > counter=0
:: > class Count:
:: >  def __init__(self):
:: >     print counter
:: > Count()
:: > 
:: > gets :
:: > 
:: > 0
:: > Process completed successfully
:: > 
:: > But:
:: > 
:: > counter=0
:: > class Count:
:: >  def __init__(self):
:: >   counter=counter+1
:: >   print counter
:: > Count()
:: > 
:: > gets:
:: > 
:: > Traceback (innermost last):
:: >   File "C:\temp\test.py", line 6, in ?
:: >     Count()
:: >   File "C:\temp\test.py", line 4, in __init__
:: >     counter=counter+1
:: > NameError: counter
:: > 
:: > Process completed with exit code 1
:: </quote>
:: 
:: Use the "global" statement, i.e. "global counter" within
:: __init__.


Additionally, Arthur, you would probably benefit from reading
(rereading?) the Python Tutorial, Chapter 9, Section 2 -- "Python Scopes
and Name Spaces," so as to have an overview of why global is necessary
here.