reference vs. name space question

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Oct 9 20:52:35 EDT 2010


On Sat, 09 Oct 2010 12:44:29 -0700, chad wrote:

> Given the following...
> 
> [cdalten at localhost oakland]$ python
> Python 2.6.2 (r262:71600, May  3 2009, 17:04:44) [GCC 4.1.1 20061011
> (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or
> "license" for more information.
>>>> class foo:
> ...   x = 1
> ...   y = 2
> ...
>>>> one = foo()
>>>> two = foo()
>>>> print one
> <__main__.foo instance at 0xb7f3a2ec>
>>>> print two
> <__main__.foo instance at 0xb7f3a16c>
>>>> one.x
> 1
> 
> 
> Is 'one' a reference or a name space?  Also, in 'one.x'. would 'one'
> be the name space?

'one' is a name. Since it is a bound name, it naturally refers to some 
object (in this case an instance of foo), which also makes it a reference.

The object that 'one' is bound to is the namespace. The name itself is 
not -- the name itself comes *from* a namespace (in this case the global 
namespace).

However, since people are lazy, and 98% of the time it makes no 
difference, and it is long and tedious to say "the object which the name 
'one' is bound to is a namespace", people (including me) will often 
shorten that to "'one' is a namespace". But remember that when people use 
a name sometimes they're talking about the name itself and sometimes the 
object it is bound to:

>>> x = 123  # x applies to the name 'x'.
>>> print x  # x applies to the object the name is bound to
123
>>> del x  # x applies to the name 'x'


Not all names are references:

>>> spam
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined

Since the name 'spam' is not bound to any object, it is not a reference. 
Likewise, given:

def func(x, y):
    pass


the name 'func' is a name which is bound to a function object. The 
function object includes two names 'x' and 'y'. Since they're not bound 
to anything, they are not references *yet*, but when you call the 
function, they become (temporarily) bound.


Hope this helps.



-- 
Steven



More information about the Python-list mailing list