-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patha_encapsulation.py
79 lines (67 loc) · 1.38 KB
/
a_encapsulation.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
75
76
77
78
79
# a_encapsulation.py
from textwrap import dedent
class Bob:
def __init__(self):
self._name = "Bob"
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, value: str):
self._name = value
def __repr__(self):
return f"{self._name}"
class Leaky:
def __init__(self, n: int, lst: list):
self._n: int = n
self._lst: list = lst
self._bob: Bob = Bob()
@property
def n(self) -> int:
return self._n
@property
def lst(self) -> list:
return self._lst
@property
def bob(self) -> Bob:
return self._bob
def __repr__(self):
return dedent(
f"""
{type(self).__name__}:
n: {self._n}
lst: {self._lst}
bob: {self._bob}
"""
)
# ... Also might need comparison, hashcode etc.
def check_for_leaks(klass) -> tuple[str, str]:
obj = klass(42, ["x", "y"])
before = repr(obj)
nn = obj.n
nn += 1
lst = obj.lst
lst.append("z")
b = obj.bob
b.name = "Ralph"
return before, repr(obj)
def test_leaks():
before, after = check_for_leaks(Leaky)
assert (
before
== """
Leaky:
n: 42
lst: ['x', 'y']
bob: Bob
"""
)
assert (
after
== """
Leaky:
n: 42
lst: ['x', 'y', 'z']
bob: Ralph
"""
)