-
Notifications
You must be signed in to change notification settings - Fork 1
/
e_copy.py
74 lines (58 loc) · 1.36 KB
/
e_copy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 容器对象
import copy
# int a = 1;
a = [1,2,3]
aa = a
print(f"{id(a) = }")
print(f"{id(aa) = }")
b = [[1], [2], [3]]
c = copy.copy(b)
print(f"{b = }")
print(f"{c = }")
print(f"{id(b[0]) = }")
print(f"{id(c[0]) = }")
print(f"{id(b) = }")
print(f"{id(c) = }")
# b =[[1], [2], [3]]
# c =[[1], [2], [3]]
c[0] = ['???']
print(f"{b = }")
print(f"{c = }")
print(f"{id(b[0]) = }")
print(f"{id(c[0]) = }")
b = [[1], [2], [3]]
c = copy.deepcopy(b)
print(f"{b = }")
print(f"{c = }")
print(f"{id(b[0]) = }")
print(f"{id(c[0]) = }")
print(f"{id(b) = }")
print(f"{id(c) = }")
from __future__ import annotations
class A:
def __init__(self) -> None:
self.a = [1,2,3]
self.b = {"1": 1}
def __copy__(self) -> A:
print(f"calling copy on {self}")
cls = self.__class__
result = cls.__new__(cls)
result.__dict__.update(self.__dict__)
return result
def __deepcopy__(self, memo):
print(f"calling deepcopy on {self}")
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, copy.deepcopy(v, memo))
return result
a = A()
b = copy.copy(a)
c = copy.deepcopy(a)
print(f"{id(a) = }")
print(f"{id(b) = }")
print(f"{id(c) = }")
print(f"{id(a.a) = }")
print(f"{id(b.a) = }")
print(f"{id(c.a) = }")