[Tutor] Variable Modification in a class
Mehta, Anish
Anish.Mehta@enst-bretagne.fr
Tue Jun 3 15:31:16 2003
Thanks to everyone for giving consideration to my problem. It worked
with copy module and it made me learn quite a few new things abt python.
Thanks for your support.
Regards,
Anish
Danny Yoo wrote:
>On Tue, 3 Jun 2003, Mehta, Anish wrote:
>
>
>
>>I m sorry that i am repeating my last mail. Here also in c i m doing the
>>same thing. Or is there any differnce? The point is clear to me that
>>when i do ' c = b' it makes the memory locations same.
>>
>>C example which is creating the confusion:
>>
>>typedef struct ab
>>{
>> int a;
>> int b;
>>}AB;
>>
>>main()
>>{
>> AB b;
>> AB c;
>>
>> b.a = 5;
>> b.b = 10;
>>
>> c = b;
>>
>> c.a = 30;
>> c.b = 40;
>>
>> printf("AB values %d %d\n", b.a, b.b);
>> printf("New values %d %d\n", c.a, c.b);
>>}
>>
>>
>
>
>Let me see if I can translate the situation in C code.
>
>/******/
>AB* b = malloc(sizeof(AB));
>AB* c = malloc(sizeof(AB));
>b->a = 5;
>b->b = 10;
>
>c = b; /** This is the crucial line. */
>/******/
>
>
>
>The equivalent Python code is:
>
>###
>b = AB()
>c = AB
>b.a = 5
>b.b = 10
>
>c = b ## This is the crucial line.
>###
>
>Does this make sense? Names in Python are things that point to objects.
>Since you're a C programmer, I think you'll understand this: in Python,
>everything's a pointer. That is, all object access in Python goes through
>a level of indirection.
>
>
>
>The confusion that you're running into is related to the way C allows for
>two different ways of working with structures: direct access, like
>
>/***/
>AB some_object;
>/***/
>
>vs indirect access through a pointer:
>
>/***/
>AB* some_object = malloc(sizeof(AB));
>/***/
>
>
>If you keep in your head that Python always uses the indirect method, the
>problem you're running into should be immediately clear.
>
>
>What you want to do, instead of reassigning c to b, is to make a copy of
>b, and assign that copy to c. We can do this with the copy module:
>
> http://www.python.org/doc/lib/module-copy.html
>
>
>
>
>