class vs function ???

Sean Ross sross at connectmail.carleton.ca
Sat Feb 21 13:20:06 EST 2004


"Gaurav Veda" <gveda at iitk.ac.in> wrote in message
news:1c764367.0402210857.579f59ab at posting.google.com...
[snip]
> a = 1
> print a
> def fun1():
>     global b
>     b = "inside fun1"
>     print b
> fun1()
> def c1():
>     print a
>     print b
>     c = 12
>     def fun2():
>         global d
>         d = "We are dead !!!"
>         print d
>     fun2()
> c1()
> class c2:
>     pass
> print d
> print c
[snip]
> Traceback (most recent call last):
>   File "XYZ.py", line 21, in ?
>     print c
> NameError: name 'c' is not defined
>
> Waiting for some 'logical' explanation !!!

The error message _is_ the logical explanation:

The name 'c' has not been defined in the scope where
'print c' is called.

You have a variable 'c' earlier in the code, yes, but that
c is a local variable of function c1(), i.e., the name 'c' _is_
defined in the scope of that function (but _only_ in that
scope). It is _not_ defined at the program scope, which
is where you've tried to use it.

I'll avoid going over Python's scoping rules here, they can
be found elsewhere. Good luck,

Sean





More information about the Python-list mailing list