测试http://www.cnblogs.com/CHYGO/articles/1916427.html的深拷贝的代码
时间: 2023-10-07 19:09:01 浏览: 92
likeke00.github.io:https://www.cnblogs.comthanksblogp12900165.html
5星 · 资源好评率100%
好的,这是一段实现深拷贝的代码,您可以测试一下:
```python
import copy
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Company:
def __init__(self, name, boss, employees):
self.name = name
self.boss = boss
self.employees = employees
boss = Person("Jack", 40)
employees = [Person("Tom", 20), Person("Jerry", 22)]
company1 = Company("ABC", boss, employees)
company2 = copy.deepcopy(company1)
print(company1.name) # ABC
print(company1.boss.name) # Jack
print(company1.employees[0].name) # Tom
print(company2.name) # ABC
print(company2.boss.name) # Jack
print(company2.employees[0].name) # Tom
company1.boss.name = "John"
company1.employees[0].name = "Jim"
print(company1.boss.name) # John
print(company1.employees[0].name) # Jim
print(company2.boss.name) # Jack
print(company2.employees[0].name) # Tom
```
输出结果应该是:
```
ABC
Jack
Tom
ABC
Jack
Tom
John
Jim
Jack
Tom
```
可以看到,使用深拷贝后,company2 和 company1 完全独立,修改 company1 中的 boss 和 employees 并不会影响 company2 中的数据。
阅读全文