Scope and classes

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Aug 18 19:39:38 EDT 2009


On Tue, 18 Aug 2009 15:47:09 -0700, David 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)?

It's a deliberate design decision. I don't recall the reasons for it, but 
the class namespace is deliberately excluded from the method scope.

The correct way of writing the above is:

class Abc:
    message = 'Hello World'
    def print_message(self):
        print self.message


self.message will first search the instance namespace for an attribute 
`message`, then search the class, then any superclasses. If you 
specifically want the class attribute, even if the instance masks it with 
an instance attribute of the same name, you do this instead:

        print self.__class__.message



-- 
Steven



More information about the Python-list mailing list