Variable Modifications in a class

Steven Taschuk staschuk at
Tue Jun 3 20:27:58 CEST 2003

Quoth Mehta, Anish:
>   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. [...]

(Nitpick: That's C++.)

> 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:
>   b.a = 5;
>   b.b = 10;
>   c = b;
>   c.a = 30;
>   c.b = 40;

In this example you're changing all the attributes of the copy, so
you might as well just make a new object from scratch.

    class AB(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b

    x = AB(5, 10)
    y = AB(30, 40)

If, however, you want to change only some attributes of the copy,
letting others take their values from the original, then asking
for a copy explicitly is indicated:

    import copy
    x = AB(5, 10)
    y = copy.copy(x)
    y.a = 30

It's not clear from your example whether copy.copy or
copy.deepcopy is appropriate.  Perhaps neither is appropriate, and
you want your own copying logic:

    class AB(object):
        def __init__(self, a, b):
            # as before
        def copy(self):
            # construct a new AB as desired and return it

    x = AB(5, 10)
    y = x.copy()
    y.a = 30

Steven Taschuk                          staschuk at
"Its force is immeasurable.  Even Computer cannot determine it."
                           -- _Space: 1999_ episode "Black Sun"

More information about the Python-list mailing list