How to Teach Python "Variables"
hdante
hdante at gmail.com
Tue Nov 27 13:21:36 EST 2007
On Nov 26, 7:49 am, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> greg <g... at cosc.canterbury.ac.nz> writes:
> > none wrote:
> >> IIRC, I once saw an explanation how Python doesn't have
> >> "variables" in the sense that, say, C does, and instead has bindings
> >> from names to objects.
>
> > If you're talking to C programmers, just tell them that Python
> > variables always contain pointers. That should give them the right
> > mental model to build on.
>
> That is a convenient shortcut when it works, but in my experience it
> tends to confuse the issue. The reason is that one of the main uses
> of pointers in C is implementing pass-by-reference. A C programmer
> told that Python variables internally hold pointers expects this code:
>
> def func(a):
> a = 10
> ...
> func(x)
>
> to change the value of x.
This shouldn't confuse a C programmer if he understands that
assignment changes the pointer address, instead of copying the value:
void func(int *a) {
int *tmp = malloc(sizeof(int));
*tmp = 10;
a = tmp;
free(tmp);
}
int *x = some_address;
func(x);
assert(x == some_address);
The confusion is that assignment does not copy the object. Python
variables are pointers and that's it.
More information about the Python-list
mailing list