Python Deep Radiation

Asked 2 years ago, Updated 2 years ago, 97 views

Hello, I'm asking you a question because I'm having a hard time copying the object instance.

import copy

class exC:
    a = None
    b = None


instA = exC()
instA.a = 5
instA.b = 5

instB = copy.deepcopy(instA)

print(id(instA))
print(id(instB))

print(id(instA.a))
print(id(instB.a))

When I execute the above code, the expected value is that the address of instA.a and the address of instB.a come out differently, but the actual execution value comes out the same. How can I change the variables inside the class to new variables?

python copy

2022-09-22 08:26

1 Answers

Hello!

import copy

a = 5
b = copy.deepcopy(a)
print(type(a))
print(id(a)) // same
print(id(b)) // same

c = [1,2]
d = copy.deepcopy(c)
print(type(c))
print(id(c)) //Different
print(id(d)) //Different
print(id(c[0])) // same
print(id(d[0])) // same

I don't think a single type has a deep copy concept. If you want to change even the variables inside the class to a new variable, it changes when you initialize to a new value instead of 5.

import copy

class exC:
    a = None
    b = None


instA = exC()
instA.a = 5
instA.b = 5

instB = copy.deepcopy(instA)
instB.a = 6 // this part 
print(id(instA))
print(id(instB))

print(id(instA.a)) // different
print(id(instB.a)) // different

Thank you for your help.


2022-09-22 08:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.