Scope and classes
Chris Rebert
clp2 at rebertia.com
Tue Aug 18 19:16:07 EDT 2009
On Tue, Aug 18, 2009 at 3:47 PM, 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)?
A class' scope is never consulted when resolving variable names in its methods.
The scopes consulted are roughly (and in this order):
1. Local variable scope (i.e. of the current function/method)
2. Enclosing functions (if you have functions nested inside other functions)
3. Globals (i.e. module-level variables)
3. Builtins (i.e. the built-in functions and methods, such as len())
To access class-level variables from within instance methods of the
class, you have 2 options:
A. Use the class name, i.e. Abc.message
B. Reference the class indirectly, i.e. self.__class__.message
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list