Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3565

Re: Namespaces in functions vs classes

Date 2011-04-19 10:58 -0400
Subject Re: Namespaces in functions vs classes
From Gerald Britton <gerald.britton@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.563.1303225104.9059.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar


Thread

Re: Namespaces in functions vs classes Gerald Britton <gerald.britton@gmail.com> - 2011-04-19 10:58 -0400

csiph-web