Newbie scopes question

Jeff Shannon jeff at ccvcorp.com
Thu Feb 28 15:54:05 EST 2002


"Gonçalo Rodrigues" wrote:

> As far as i understand, a class statement opens a new scope.
>
> In the following piece of code
>
> class Outer:
>     attribute = "The outer class attribute"
>
>     def __init__(self):
>         try:
>             print attribute
>         except NameError:
>             print "Attribute not defined!"
>
> def Outer_function():
>     local_var = "Local var of the outer function"
>
>     def inner_function():
>         print local_var
>
>     inner_function()
>
> Outer_function()
> a = Outer()
>
> What we get printed is
>
> Local var of the outer function
> Attribute not defined!
>
> This means that function and class scopes behave differently as fas as
> nesting goes. Could someone explain why is this?

Because they do?  :)  Perhaps it's because the problem that nested scopes
intended to solve, never existed with classes.  In the class example, you
can always access Outer.attribute, whether inside the class (or however
deeply nested) or not.  In the function example, prior to nested scopes,
there was *no* way for inner_function() to access local_var, without
having it passed in as an argument.

It makes philosophical sense, too.  Class/instance attributes are distinct
from local variables, and it makes no sense to refer to a class attribute
without specifying the class that you're interested in.  While some
languages (such as C++) will implicitly check unqualified variables to see
if they're class attributes, this is unclear and prone to bugs (explicit
is better than implicit).

Perhaps it'd make more sense, if you think of the class statement as not
opening a new scope, but rather, opening a new namespace.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list