list storing variables
Marko Rauhamaa
marko at pacujo.net
Mon Feb 23 14:06:11 EST 2015
Peter Otten <__peter__ at web.de>:
> The OP explicitly mentions the & operator. There's no python analog to
> that and the behavior shown below:
>
> $ cat pointers.c
> #include <stdio.h>
>
> int main()
> {
> int a = 2, b = 5;
> int * Li[2] = { &a, &b };
> printf("%d %d\n", *Li[0], *Li[1]);
> a = 3;
> printf("%d %d\n", *Li[0], *Li[1]);
> return 0;
> }
> $ gcc pointers.c
> $ ./a.out
> 2 5
> 3 5
But there is! I just demonstrated it in a previous posting:
> In Python, you can accomplish "&" by creating an object:
>
> >>> a = 3
> >>> b = 4
> >>> class AmpersandA:
> ... def get(self): return a
> ... def set(self, value): global a; a = value
> ...
> >>> class AmpersandB:
> ... def get(self): return b
> ... def set(self, value): global b; b = value
> ...
> >>> l = [ AmpersandA(), AmpersandB() ]
> >>> for m in l:
> ... m.set(7)
> ...
> >>> print(a)
> 7
> >>> print(b)
> 7
> >>>
>
> It's exactly like "&" in C escept it's a slight bit more verbose and the
> exact implementation is dependent on the name of the variable.
You can find an analogous ampersand object for any C lvalue.
What I'm saying is that there's nothing special about Python's object
model or variables. Guido could decide tomorrow to add a C-esque "&"
operator to Python without breaking a single existing Python program.
The Python compiler would simply generate code like above.
Marko
More information about the Python-list
mailing list