Namespaces in functions vs classes

Gerald Britton gerald.britton at gmail.com
Tue Apr 19 16:58:21 CEST 2011


Ethan -- I'm just getting back to this question.  If you recall, you asked:

[snip]

8<----------------------------------------------------
"script with possible name clashes"

eggs = 'scrambled eggs'
meat = 'steak'

class Breakfast():
     meat = 'spam'
     def serve(self):
         print("Here's your %s and %s!" %
                (eggs, meat))

Breakfast().serve()
8<----------------------------------------------------

>What will serve print?

Well, I think it should print the same thing as:

def Breakfast():
    meat = 'spam'
    def serve(self):
        print("Here's your %s and %s!" %
               (eggs, meat))
    return serve(None)

Breakfast()

but it doesn't!  The function definition uses the local (to the
function) variable "meat", whereas the class method uses the global
definition of "meat".  The class attribute "meat" is not seen by the
serve method unless it is qualified.  I now understand the Python does
not consider a class definition as a separate namespace as it does for
function definitions.  That is a helpful understanding.

Anyway, thanks for jumping in to the discussion.

-- 
Gerald Britton



More information about the Python-list mailing list