Objects in Python

Chris Angelico rosuav at gmail.com
Fri Aug 24 03:34:02 CEST 2012


On Fri, Aug 24, 2012 at 10:36 AM, Roy Smith <roy at panix.com> wrote:
> 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

Ah, no. What you have there is actually id(4) and nothing to do with a at all.

> 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).

And you now have id(123) - of course, it's possible for there to be
two integer objects with the value 123, but what I'm emphasizing is
that you're not looking at a here.

> 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.

Try this instead. It's C++ not C but a much closer match. You could
instead play with malloc if you want it to be C.

#include <stdio.h>

main()
{
    int *a=new int(40);
    printf("a = %d, id(a) = %p\n",*a,a);
    a=new int(99);
    printf("a = %d, id(a) = %p\n",*a,a);
}

I've not tested the code and may have a syntax issue with "new
int(40)" (who ever allocates a single int on the heap??) but you get
the idea. At no point do you ever look at, or need to look at, &a.
That's utterly irrelevant.

ChrisA



More information about the Python-list mailing list