Objects in Python
Roy Smith
roy at panix.com
Thu Aug 23 20:36:27 EDT 2012
In article <mailman.3693.1345697563.4697.python-list at python.org>,
Evan Driscoll <driscoll at cs.wisc.edu> wrote:
> > In fact, Python doesn't have variables not as C or Java programmers
> > would understand the term. What it has instead are references to objects
> > (with names as one kind of reference).
>
> OK, I've seen this said a few times, and I have to ask: what do you mean
> by this? I consider myself pretty decent at Python and other languages,
> and I really don't get it.
I'll take a shot at this.
When I execute:
a = 4
I'm doing two things. The first is to create an object of type int with
a value of 4. I think everybody is OK with that part. The confusing
part comes with the LHS.
In C, or Java, there's a container called "a" which holds a value. In
C, that value is the integer 4, in Java it's an Integer object (well, at
least I think it is, I've never fully groked how Java handles integers).
In Python, there is no container named "a". There is, however, a dict
which exists somewhere in python-space. You can get a reference to this
dict by calling globals(). What the assignment does is effectively:
globals()["a"] = 4
In fact, I can even write it that way and everything works:
>>> globals()["a"] = 42
>>> a
42
Even id() thinks they're the same thing:
>>> id(a)
1755402140
>>> id(globals()["a"])
1755402140
But, notice what happens if I now assign something new to a:
>>> a = 123
>>> id(a)
1755403176
The id has changed! Now, we all know that the id of an object is its
memory address (that's not guaranteed, but in the standard C
implementation of Python, that's what it is).
Now, what if I do something similar in C:
#include <stdio.h>
main() {
int a = 40;
printf("a = %d, &a = %p\n", a, &a);
a = 99;
printf("a = %d, &a = %p\n", a, &a);
}
When I compile and run this, it prints:
a = 40, &a = 0x7fff1911f5bc
a = 99, &a = 0x7fff1911f5bc
Notice that the address of the variable "a" didn't change when I
assigned it a new value. That's what people mean when they say C has
variables and Python doesn't; it just binds names to values.
More information about the Python-list
mailing list