深拷贝和浅拷贝的代码示例
时间: 2023-06-01 19:05:49 浏览: 93
好的,以下是深拷贝和浅拷贝的代码示例:
浅拷贝:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."
def copy(self):
return Person(self.name, self.age)
# 创建一个Person对象
p1 = Person("Alice", 30)
# 进行浅拷贝
p2 = p1.copy()
p1.age = 25
# p2的年龄也会被改变,因为是浅拷贝
print(p1) # 输出: Alice is 25 years old.
print(p2) # 输出: Alice is 30 years old.
```
深拷贝:
```python
import copy
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."
def copy(self):
return Person(self.name, self.age)
def deep_copy(self):
return copy.deepcopy(self)
# 创建一个Person对象
p1 = Person("Alice", 30)
# 进行深拷贝
p2 = p1.deep_copy()
p1.age = 25
# p2的年龄不会被改变,因为是深拷贝
print(p1) # 输出: Alice is 25 years old.
print(p2) # 输出: Alice is 30 years old.
```
希望可以帮到你。
阅读全文