Namespaces in functions vs classes

G

Gerald Britton

I apologize if this has been answered before or if it is easy to find
in the docs. (I couldn't find it but might have missed it)

I'm trying to understand the differences between namespaces in class
definitions vs. function definitions. Consider this function:
.... foo = 'foo'
.... def g(x):
.... return foo
.... print g(1)
....
Now, I replace the first "def" with "class":
.... foo = 'foo'
.... def g(x):
.... return foo
.... print g(1)
....
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in a
File "<stdin>", line 4, in g
NameError: global name 'foo' is not defined

So, the variable "foo" is not available inside the function inside
class as it is inside the (inner) function. I figured this was just
because the class was still being defined, so I tried this:
.... foo = 'foo'
.... def g(x):
.... return foo
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>

which still fails. I had expected that "foo" would be available
within the namespace of the object instance. I was wrong. For my
final attempt, I add the prefix "a." to my use of "foo"
.... foo = 'foo'
.... def g(x):
.... return a.foo
....'foo'

So, this works and I can use it. However, I would like a deeper
understanding of why I cannot use "foo" as an unqualified variable
inside the method in the class. If Python allowed such a thing, what
problems would that cause?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top