Can you help me solve this?

Pieter van Oostrum pieter-l at vanoostrum.org
Mon Mar 16 18:26:51 EDT 2020


Pieter van Oostrum <pieter-l at vanoostrum.org> writes:

> Joseph Nail <joseph2001nail at gmail.com> writes:
>
>> Hello,
>> I have one problem. Somehow in my function when I wrote y=x, they are the
>> same variable and then it also changes age or height (which were x) in the
>> main program. See more in attached file.
>> Maybe it is bug or maybe it should run that way.
>
> If you write y = x, then they are not the same variable, but they point
> to (the proper Python language is they are bound to) the same object.
>
> Now if you say x.age = 20, then y.age will also be 20 (it's the same object).

If you want y to be an independent copy of x (i.e. a new object that has the same values), use:

import copy
y = copy.copy(x)

Now you can change x.age and it won't affect y.age
-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]


More information about the Python-list mailing list