Skip to content

Commit ca049e9

Browse files
committed
revised examples for chapter 9
1 parent 812d416 commit ca049e9

File tree

3 files changed

+185
-25
lines changed

3 files changed

+185
-25
lines changed

classes/private/Confidential.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
public class Confidential {
22

3-
private String secret = "";
4-
private String hidden = "burn after reading";
3+
private String secret = "";
54

6-
public Confidential(String text) {
7-
this.secret = text.toUpperCase();
8-
}
5+
public Confidential(String text) {
6+
secret = text.toUpperCase();
7+
}
98
}

classes/private/Expose.java

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,24 @@
22

33
public class Expose {
44

5-
public static void main(String[] args) {
6-
Confidential message = new Confidential("top secret text");
7-
Field secretField = null;
8-
try {
9-
secretField = Confidential.class.getDeclaredField("secret");
10-
}
11-
catch (NoSuchFieldException e) {
12-
System.err.println(e);
13-
System.exit(1);
14-
}
15-
secretField.setAccessible(true); // break the lock!
16-
try {
17-
String wasHidden = (String) secretField.get(message);
18-
System.out.println("message.secret = " + wasHidden);
19-
}
20-
catch (IllegalAccessException e) {
21-
// this will not happen after setAcessible(true)
22-
System.err.println(e);
23-
}
24-
}
5+
public static void main(String[] args) {
6+
Confidential message = new Confidential("top secret text");
7+
Field secretField = null;
8+
try {
9+
secretField = Confidential.class.getDeclaredField("secret");
10+
}
11+
catch (NoSuchFieldException e) {
12+
System.err.println(e);
13+
System.exit(1);
14+
}
15+
secretField.setAccessible(true); // break the lock!
16+
try {
17+
String wasHidden = (String) secretField.get(message);
18+
System.out.println("message.secret = " + wasHidden);
19+
}
20+
catch (IllegalAccessException e) {
21+
// this will not happen after setAcessible(true)
22+
System.err.println(e);
23+
}
24+
}
2525
}

classes/vector2d_v3_prophash.py

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
"""
2+
A 2-dimensional vector class
3+
4+
>>> v1 = Vector2d(3, 4)
5+
>>> print(v1.x, v1.y)
6+
3.0 4.0
7+
>>> x, y = v1
8+
>>> x, y
9+
(3.0, 4.0)
10+
>>> v1
11+
Vector2d(3.0, 4.0)
12+
>>> v1_clone = eval(repr(v1))
13+
>>> v1 == v1_clone
14+
True
15+
>>> print(v1)
16+
(3.0, 4.0)
17+
>>> octets = bytes(v1)
18+
>>> octets
19+
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
20+
>>> abs(v1)
21+
5.0
22+
>>> bool(v1), bool(Vector2d(0, 0))
23+
(True, False)
24+
25+
26+
Test of ``.frombytes()`` class method:
27+
28+
>>> v1_clone = Vector2d.frombytes(bytes(v1))
29+
>>> v1_clone
30+
Vector2d(3.0, 4.0)
31+
>>> v1 == v1_clone
32+
True
33+
34+
35+
Tests of ``format()`` with Cartesian coordinates:
36+
37+
>>> format(v1)
38+
'(3.0, 4.0)'
39+
>>> format(v1, '.2f')
40+
'(3.00, 4.00)'
41+
>>> format(v1, '.3e')
42+
'(3.000e+00, 4.000e+00)'
43+
44+
45+
Tests of the ``angle`` method::
46+
47+
>>> Vector2d(0, 0).angle()
48+
0.0
49+
>>> Vector2d(1, 0).angle()
50+
0.0
51+
>>> epsilon = 10**-8
52+
>>> abs(Vector2d(0, 1).angle() - math.pi/2) < epsilon
53+
True
54+
>>> abs(Vector2d(1, 1).angle() - math.pi/4) < epsilon
55+
True
56+
57+
58+
Tests of ``format()`` with polar coordinates:
59+
60+
>>> format(Vector2d(1, 1), 'p') # doctest:+ELLIPSIS
61+
'<1.414213..., 0.785398...>'
62+
>>> format(Vector2d(1, 1), '.3ep')
63+
'<1.414e+00, 7.854e-01>'
64+
>>> format(Vector2d(1, 1), '0.5fp')
65+
'<1.41421, 0.78540>'
66+
67+
# BEGIN VECTOR2D_V3_DEMO
68+
Tests of `x` and `y` read-only properties:
69+
70+
>>> v1.x, v1.y
71+
(3.0, 4.0)
72+
>>> v1.x = 123
73+
Traceback (most recent call last):
74+
...
75+
AttributeError: can't set attribute
76+
77+
# END VECTOR2D_V3_HASH_DEMO
78+
79+
Tests of hashing:
80+
# BEGIN VECTOR2D_V3_HASH_DEMO
81+
82+
>>> v1 = Vector2d(3, 4)
83+
>>> v2 = Vector2d(3.1, 4.2)
84+
>>> hash(v1), hash(v2)
85+
(7, 384307168202284039)
86+
>>> len(set([v1, v2]))
87+
2
88+
89+
# END VECTOR2D_V3_DEMO
90+
91+
"""
92+
93+
from array import array
94+
import math
95+
96+
# BEGIN VECTOR2D_V3_PROP
97+
class Vector2d:
98+
typecode = 'd'
99+
100+
def __init__(self, x, y):
101+
self.__x = float(x) # <1>
102+
self.__y = float(y)
103+
104+
@property # <2>
105+
def x(self): # <3>
106+
return self.__x # <4>
107+
108+
@property # <5>
109+
def y(self):
110+
return self.__y
111+
112+
def __iter__(self):
113+
return (i for i in (self.x, self.y)) # <6>
114+
115+
# remaining methods follow (omitted in book listing)
116+
# END VECTOR2D_V3_PROP
117+
118+
def __repr__(self):
119+
class_name = type(self).__name__
120+
return '{}({!r}, {!r})'.format(class_name, *self)
121+
122+
def __str__(self):
123+
return str(tuple(self))
124+
125+
def __bytes__(self):
126+
return (bytes([ord(self.typecode)]) +
127+
bytes(array(self.typecode, self)))
128+
129+
def __eq__(self, other):
130+
return tuple(self) == tuple(other)
131+
132+
# BEGIN VECTOR_V3_HASH
133+
def __hash__(self):
134+
return hash(self.x) ^ hash(self.y)
135+
# END VECTOR_V3_HASH
136+
137+
def __abs__(self):
138+
return math.hypot(self.x, self.y)
139+
140+
def __bool__(self):
141+
return bool(abs(self))
142+
143+
def angle(self):
144+
return math.atan2(self.y, self.x)
145+
146+
def __format__(self, fmt_spec=''):
147+
if fmt_spec.endswith('p'):
148+
fmt_spec = fmt_spec[:-1]
149+
coords = (abs(self), self.angle())
150+
outer_fmt = '<{}, {}>'
151+
else:
152+
coords = self
153+
outer_fmt = '({}, {})'
154+
components = (format(c, fmt_spec) for c in coords)
155+
return outer_fmt.format(*components)
156+
157+
@classmethod
158+
def frombytes(cls, octets):
159+
typecode = chr(octets[0])
160+
memv = memoryview(octets[1:]).cast(typecode)
161+
return cls(*memv)

0 commit comments

Comments
 (0)