Variable Modifications in a class
Bernard Yue
bernie at 3captus.com
Tue Jun 3 14:27:07 EDT 2003
Mehta, Anish wrote:
> Thanks for the explaination. That point is clear and also one thing
> more is that when we have the same piece of code in c , and when we do
> 'c = b' then copy constructor is invoked. So in c with the
> same(likely) piece of code we have differnt output from python. I
> would like to know is there any way with which i can write the code in
> python for the C code like below.
> I am writing a program in python which is already written in C and in
> that lot of instances are modifying the variables of the some
> structure like this:
>
>
> 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);
> }
>
> The output is:
>
> AB values 5 10
> New values 30 40
use module copy. Code as follows:
import copy
class AB:
def __init__(self):
self.a = None
self.b = None
def func(ab):
b = ab()
# c = ab()
b.a = 5
b.b = 10
c = copy.deepcopy(b)
c.a = 30
c.b = 40
print b.a, b.b
print c.a, c.b
t = func(AB)
>
>> So let's run through your function line by line
>>
>> def func(ab):
>> b = ab()
>>
>> This creates a new AB object, the first one.
>> It also creates the name "b", and binds it to the new AB object.
>>
>> c = ab()
>>
>> This also creates a new (and different) AB object, the second one.
>> It also creates the name "c", and binds it to the second AB object.
>>
>> b.a = 5
>>
>> Set the "a" member of the AB object *referred to* to by "b" to 5
>>
>> b.b = 10
>>
>> Set the "b" member of the AB object *referred to* to by "b" to 10
>>
>> c = b
>>
>> Make the name "c" refer to whatever "b" refers to
>> (in this case, the *first* AB object).
>> Note also that you now have no way of getting at the second AB
>> object, since you have no reference to it. It has fallen into the
>> garbage heap, and will be recycled eventually.
>>
>> c.a = 30
>>
>> Set the "a" member of the AB object referred to by c (i.e. the first AB
>> object) to 30
>>
>> c.b = 40
>>
>> Set the "b" member of the AB object referred to by c (i.e. the first AB
>> object) to 40
>>
>> I think you will understand the behaviour better now.
>>
>> HTH,
>>
>>
>>
>
>
>
More information about the Python-list
mailing list