Scope and classes

Jan Kaliszewski zuo at chopin.edu.pl
Wed Aug 19 02:10:58 CEST 2009


19-08-2009 o 00:47:09 David <davidshais at googlemail.com> wrote:

> Hi all,
>
> I'm trying to understand how scopes work within a class definition.
> I'll quickly illustrate with an example. Say I had the following class
> definition:
>
> class Abc:
>     message = 'Hello World'
>
>     def print_message(self):
>         print message
>
>>>> instance = Abc()
>>>> instance.print_message()
> NameError: global name 'message' not defined
>
> My question is, why? message is not defined in print_message, but it
> is defined in the enclosing scope (the class)?

Note that when *running* the code that is *inside* print_message() method
called within the global scope, the outer (enclosing) scope is indeed the
global scope (the scope in which e.g. 'instance' name exists; note that
e.g. 'print instance' in that method would be ok).

As Chris wrote, class' scope (contrary to outer function scope) is not
considered as the 'enclosing' scope.

The only ways to reach Abc's attribute 'message' from that method are:
* 'Abc.message'
* 'self.__class__.message'
* 'self.message' (unless there is an instance attribute 'message' which
overrides the class attribute).

Cheers,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list