Answer the question
In order to leave comments, you need to log in
Why doesn't the shallow copy change the value?
There is a problem on Creation of a copy . And when we create a shallow copy of an instance x y=copy(x), then according to the idea, we should change 2 values name and nums. But only nums changes, the code is below. I can not catch up with this moment why so? About the complete lists is understandable.
from copy import copy, deepcopy
class MyClass:
def __init__(self, name, nums):
self.name=name
self.nums=nums
def show(self):
print("name ->", self.name)
print("nums ->", self.nums)
x=MyClass("Python", [1,2,3])
print("Экземпляр х:")
x.show()
#копии - поверхностная, полная
y=copy(x)
z=deepcopy(x)
print("Экземпляр y:")
y.show()
print("Экземпляр z:")
z.show()
print("Поля экземпляра х изменяются")
x.name="Java"
x.nums[0]=0
print("Экземпляр x:")
x.show()
print("Экземпляр y:")
y.show()
print("Экземпляр z:")
z.show()
Экземпляр x:
name -> Java
nums -> [0, 2, 3]
Экземпляр y:
name -> Python Должен же измениться???
nums -> [0, 2, 3]
Экземпляр z:
name -> Python
nums -> [1, 2, 3]
Answer the question
In order to leave comments, you need to log in
everything is as it should be.
In C-like programming languages, a variable is like a box with a name. You can put a value in a box, and when assigning, another value is put in the box, and the old value will no longer be associated with this box. One box - one value.
In Python, a variable is like a label with a name. When assigning, you kind of put a label on the object:
x = [1,2,3]
y=x
And now you have two labels: x and y. Both are attached to the same object.
If you change this object (edit the element), then it does not matter how you access it, by which name.
It is necessary to distinguish between what you are changing: you are either moving the label with the name to another object, or you are changing something inside the object to which the label is attached. Feel the difference?
Imagine that your object (Application) has two attributes: Customer_Name and Apartment_Address.
You are copying the application superficially. You change the name in one of the copies, and in the second everything remains as it was. Doing repairs in the apartment at the specified address. Of course, the address in both copies of the application is the same and you did not change it. You changed the object at this address.
Now you take the request and deep copy it:
This is where the problem with the analogy comes in, but that won't hurt us.
You change the name in the copy and everything works like in the previous example.
But when creating a deep copy, a new absolutely identical apartment was created, but with a new address. The copy of the application has a different address. If you make repairs in an apartment at a new or old address, then this will not be reflected in another apartment.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question