forked from gc3-uzh-ch/python-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
part07.tex
348 lines (287 loc) · 9.13 KB
/
part07.tex
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
\documentclass[english,serif,mathserif,xcolor=pdftex,dvipsnames,table]{beamer}
\usetheme[informal]{s3it}
\usepackage{s3it}
\title[Special methods]{%
Special methods
}
\author[S3IT]{%
S3IT: Services and Support for Science IT, \\
University of Zurich
}
\date{June~23--24, 2014}
\begin{document}
% title frame
\maketitle
\begin{frame}
\frametitle{What we shall see in this part}
How to define custom behavior for Python's standard operators and
functions on user-defined objects.
\+
(Technically called ``operator overloading.'')
\end{frame}
\begin{frame}[fragile]
\frametitle{Python's special methods}
\textbf{Names that start and end with two underscores (e.g.,
\lstinline|__init__|) have a special significance in Python.}
\+
However, there is nothing special in the way we define those
methods: the syntax is the same as for any other method.
\+ Most of the special methods directly map to Python's operators (e.g.,
``\texttt{+}'', ``\texttt{==}'' or ``\texttt{in}'').
\+
\begin{references}
\url{http://docs.python.org/2/reference/datamodel.html#special-method-names}
\end{references}
\end{frame}
\begin{frame}[fragile]
\frametitle{First Example (1/2)}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector(object):
"""A 2D Vector."""
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, other):
return Vector(self.x+other.x,
self.y+other.y)
def mul(self, scalar):
return Vector(scalar*self.x, scalar*self.y)
def ~\HL{\_\_str\_\_}~(self):
return ("<%g,%g>" % (self.x, self.y))
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
Let us rename the \texttt{show} method to \texttt{\_\_str\_\_}.
\end{column}
\end{columns}
\+
{\scriptsize Source code available at:
\url{https://raw.github.com/gc3-uzh-ch/python-course/master/vector2.py}}
\end{frame}
\begin{frame}[fragile]
\frametitle{First Example (2/2)}
\begin{lstlisting}
>>> from vector2 import Vector
>>> v = Vector(0,1)
>>> print(v)
<0,1>
\end{lstlisting}
\+
Now Python's built-in \texttt{print} behaves like the \texttt{show} method did!
\+ Actually, \texttt{print} uses Python's built-in function
\texttt{str()} to convert an object to a string, and then prints
this string.
\+ {\bfseries By defining the \lstinline|__str__| method, we
override the default behavior of Python's \lstinline|str()| for
objects of class \texttt{Vector}.}
\end{frame}
\begin{frame}[fragile]
\frametitle{Second Example: equality testing (1/3)}
Can we test two instanced of class \texttt{Vector} for equality?
\begin{lstlisting}
>>> from vector2 import Vector
>>> v1 = Vector(0,1)
>>> v2 = Vector(0,1)
>>> v1 == v2
~\HL{False}~
\end{lstlisting}
\+ Python does not know how to test if two user defined objects are
equal.
\+ \textbf{By default ``\texttt{==}'' behaves like the
``\texttt{is}'' operator on user-defined classes}, i.e., two
user-defined objects are considered equal if and only if they are
the same object.
\+ \textbf{This can be changed by adding a \lstinline|__eq__| method.}
\end{frame}
\begin{frame}[fragile]
\frametitle{Equality \emph{vs} identity}
The \texttt{is} operator returns \texttt{True} if two names refer to
the same instance; the \texttt{==} operator compares the
\emph{values} of two objects.\footnote{A class can define how
exactly the \texttt{==} operator should carry out the comparison.}
\+
Note that two instances may be equal in any respect yet be
different instances: \emph{equality is not identity!}
\begin{python}
>>> dt4 = date(2012,9,28)
>>> dt5 = date(2012,9,28)
>>> dt4 == dt5
True
>>> dt4 is dt5
False
\end{python}
\end{frame}
\begin{frame}[fragile]
\frametitle{Second Example: equality testing (2/3)}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector(object):
"""A 2D Vector."""
def __init__(self, x, y):
self.x = x
self.y = y
# (code omitted)
def __str__(self):
return ("<%g,%g>" % (self.x, self.y))
~\HL{\textbf{def} \_\_eq\_\_(\textbf{self}, other):}~
return (self.x == other.x) and (self.y == other.y)
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
Let us add an \lstinline|__eq__|~method.
\end{column}
\end{columns}
\+
{\scriptsize Source code available at:
\url{https://raw.github.com/gc3-uzh-ch/python-course/master/vector3.py}}
\end{frame}
\begin{frame}[fragile]
\frametitle{Second Example: equality testing (3/3)}
\begin{lstlisting}
>>> from vector3 import Vector
>>> v1 = Vector(0,1)
>>> v2 = Vector(0,1)
>>> v1 == v2
True
\end{lstlisting}
\+ {\bfseries By defining the \lstinline|__eq__| method, we
define the behavior of Python's equality test \lstinline|==| for
objects of class \texttt{Vector}.}
\end{frame}
\begin{frame}[fragile]
\frametitle{3rd Example: vector addition (1/3)}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector(object):
"""A 2D Vector."""
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return ("<%g,%g>" % (self.x, self.y))
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
~\HL{\textbf{def} \_\_add\_\_(\textbf{self}, other):}~
return Vector(self.x+other.x, self.y+other.y)
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
The \lstinline|__add__| special method defines the behavior of the
``\texttt{+}'' operator.
\+
Let's just rename \texttt{add} \\ to \texttt{\_\_add\_\_}.
\end{column}
\end{columns}
\+
{\scriptsize Source code available at:
\url{https://raw.github.com/gc3-uzh-ch/python-course/master/vector3.py}}
\end{frame}
\begin{frame}[fragile]
\frametitle{3rd Example: vector addition (2/3)}
Now vector addition works with the usual ``\texttt{+}'' operator:
\begin{lstlisting}
>>> from vector4 import Vector
>>> v1 = Vector(1,0)
>>> v2 = Vector(0,1)
>>> print (v1 + v2)
<1,1>
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{3rd Example: vector addition (3/3)}
What if we add inhomogeneous objects, e.g., a vector and a number?
\begin{lstlisting}
>>> from vector4 import Vector
>>> v1 = Vector(1,0)
>>> print (v1 + 5.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "vector4.py", line 14, in __add__
return Vector(self.x+other.x, self.y+other.y)
~\HL{AttributeError: 'float' object has no attribute 'x'}~
\end{lstlisting}
\+ In this case, an error is the correct behavior: a vector can only
be summed to another vector.
\+ We shall see in the next part that sometimes it makes sense to
allow inhomogenneous operations, and how to implement them.
\end{frame}
\begin{frame}[fragile]
\frametitle{4th Example: vector multiplication (1/3)}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector(object):
"""A 2D Vector."""
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return ("<%g,%g>" % (self.x, self.y))
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __add__(self, other):
return Vector(self.x+other.x, self.y+other.y)
~\HL{\textbf{def} \_\_mul\_\_(\textbf{self}, scalar):}~
return Vector(scalar*self.x, scalar*self.y)
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
The \lstinline|__mul__| special method defines the behavior of
the ``\texttt{*}'' operator.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{4th Example: vector multiplication (2/3)}
Now vector multiplication works with the usual ``\texttt{*}'' operator:
\begin{lstlisting}
>>> from vector5 import Vector
>>> v1 = Vector(1,2)
>>> v1 * 3 == Vector(3, 6)
>>> print (v1 * 2)
<2,4>
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{4th Example: vector multiplication (3/3)}
\small
Note that:
\begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
>>> from vector5 import Vector
>>> v1 = Vector(1,2)
>>> 3 * v1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'int' and 'Vector'
\end{lstlisting}
\+ Order matters! Our \lstinline|__mul__| method requires a \lstinline|Vector| instance first, and a number second.
\+ The operation with swapped operands is called \lstinline|__rmul__|, but treating this in detail would take us too far!
\+ Take-home message: \textbf{Operations defined with special
methods are not automatically commutative, transitive or any other
property you normally associate with the operators \texttt{+},
\texttt{*}, etc.}
\end{frame}
\begin{frame}{Further reading}
A good and readable introduction to Python's special methods:
\begin{center}
\url{http://www.rafekettler.com/magicmethods.html}
\end{center}
\+
Special methods hook directly into Python's syntax. They can
enhance readability or make code completely obscure. Use them
sparingly, and remember: \emph{with great power comes great
responsibility!}
\end{frame}
\end{document}
%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End: