forked from gc3-uzh-ch/python-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
part06.tex
638 lines (533 loc) · 15.4 KB
/
part06.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
\documentclass[english,serif,mathserif,xcolor=pdftex,dvipsnames,table]{beamer}
\usetheme[informal]{s3it}
\usepackage{s3it}
\title[OOP 1]{%
Object-orientation, I
}
\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 Python objects.
\+
We shall use \href{http://jccc-mpg.wikidot.com/vectors}{2D
vectors} as examples.
\end{frame}
\begin{frame}
\frametitle{Recall: \emph{What is an object}?}
\textbf{A Python object is a bundle of variables and functions.}
\+
What variable names and functions comprise an object is defined
by the object's \emph{class}.
\+
From one class specification, many objects can be
\emph{instanciated}. Different instances can assign different
values to the object variables.
\+
Variables and functions in an instance are collectively called
\emph{instance attributes}; functions are also termed \emph{instance
methods}.
\end{frame}
\begin{frame}
\frametitle{Recall: \emph{What is a 2D vector?}}
A \emph{2D} vector is an element of the vector space
$\mathbb{R}^2$.
\+
Every \emph{2D} vector $\mathbf{u}$ is completely described by a
pair of real coordinates $\langle u_x, u_y \rangle$.
Two operations are defined on vectors:
\+
\begin{columns}
\begin{column}{0.6\linewidth}
\raggedleft
\emph{vector addition:} if $\mathbf{w} = \mathbf{u} +
\mathbf{v}$, then $w_x = u_x + v_x$ and $w_y = u_y + v_y$.
\end{column}
\begin{column}{0.4\linewidth}
\centering
\includegraphics[height=4\baselineskip]{fig/VectorAddition.jpg}
\end{column}
\end{columns}
\+
\begin{columns}
\begin{column}{0.4\linewidth}
\centering
\includegraphics[height=3\baselineskip]{fig/VectorScalarMultiplication.jpg}
\end{column}
\begin{column}{0.6\linewidth}
\raggedright
\emph{scalar multiplication:} if $\mathbf{v} = \alpha
\cdot \mathbf{u}$ with $\alpha \in \mathbb{R}$, then $v_x =
\alpha \cdot u_x$ and $v_y = \alpha \cdot u_y$.
\end{column}
\end{columns}
\begin{references}
\tiny
Images courtesy of \url{http://jccc-mpg.wikidot.com/vectors},
which see for precise definitions and discussion of 2D vectors.
\end{references}
\end{frame}
\begin{frame}[fragile]
\frametitle{A \emph{2D vector} in Python}
\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 show(self):
return ("<%g,%g>" % (self.x, self.y))
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
This code defines a Python object that implements a 2D vector.
\end{column}
\end{columns}
\+
{\scriptsize Source code available at:
\url{https://raw.github.com/gc3-uzh-ch/python-course/master/vector.py}}
\end{frame}
\begin{frame}[fragile]
\frametitle{What does \texttt{Vector} do?}
\begin{columns}
\begin{column}[t]{0.5\linewidth}
We can create vectors by initializing them with the two coordinates
$(x,y)$:
\begin{lstlisting}
>>> u = Vector(1,0)
>>> v = Vector(0,1)
\end{lstlisting}
\end{column}
\begin{column}[t]{0.5\linewidth}
The \texttt{show} method shows vector coordinates:
\begin{lstlisting}
>>> u.show()
'<1,0>'
>>> v.show()
'<0,1>'
\end{lstlisting}
\end{column}
\end{columns}
\+
\begin{columns}
\begin{column}[t]{0.5\linewidth}
The \texttt{add} method implements vector addition:
\begin{lstlisting}
>>> w = u.add(v)
>>> w.show()
'<1,1>'
\end{lstlisting}
\end{column}
\begin{column}[t]{0.5\linewidth}
The \texttt{mul} method implements scalar multiplication:
\begin{lstlisting}
>>> v2 = v.mul(2)
>>> v2.show()
'<0,2>'
\end{lstlisting}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{User-defined classes, I}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
~\HL{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 show(self):
return ("<%g,%g>" % (self.x, self.y))
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
A class definition starts with the keyword \texttt{class}.
The class definition is indented relative to the \texttt{class}
statement.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{User-defined classes, II}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector~\HL{(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 show(self):
return ("<%g,%g>" % (self.x, self.y))
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
This identifies user-defined~classes.
\+
(Do not leave it out or you'll get an ``old-style'' class, which
is deprecated behavior.)
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{User-defined classes, II}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector(object):
~\HL{"""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 show(self):
return ("<%g,%g>" % (self.x, self.y))
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
Classes can have docstrings.
The content of a class docstring will be shown as help text for
that class.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{User-defined classes, IV}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector(object):
"""A 2D Vector."""
~\HL{\textbf{def} \_\_init\_\_(\textbf{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 show(self):
return ("<%g,%g>" % (self.x, self.y))
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
The {\bf def} keyword introduces a method~definition.
\+
Every method \emph{must} have at~least one argument,
named~{\bf self}.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{The \texttt{self} argument}
\textbf{Every method of a Python object always has \texttt{self}
as first argument.}
\+
However, you do not specify it when calling a method: it's
automatically inserted by Python:
\begin{lstlisting}
>>> class ShowSelf(object):
... def show(self):
... print(self)
...
>>> x = ShowSelf() # construct instance
>>> x.show() # `self' automatically inserted!
<__main__.ShowSelf object at 0x299e150>
\end{lstlisting}
\+
The \texttt{self} name is a reference to the object instance
itself. You \emph{need to} use \texttt{self} when accessing methods
or attributes of this instance.
\end{frame}
\begin{frame}
\frametitle{No access control}
There are no ``public''/``private''/etc. qualifiers for object
attributes.
\+
\textbf{\emph{Any} code can create/read/overwrite/delete \emph{any} attribute on
\emph{any} object.}
\+
There are \emph{conventions}, though:
\begin{itemize}
\item ``protected'' attributes: \texttt{\_name}
\item ``private'' attributes: \texttt{\_\_name}
\end{itemize}
(But again, note that this is not \emph{enforced} by the system in
any way.)
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, I}
\small
Within a function body, names are resolved according to \href{http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules/292502#292502}{the LEGB rule}:
\begin{description}
\item[L] Local scope: any names defined in the current function;
\item[E] Enclosing function scope: names defined in enclosing
functions (outermost last);
\item[G] global scope: names defined in the toplevel of the enclosing module;
\item[B] Built-in names (i.e., Python's \texttt{\_\_builtins\_\_} module).
\end{description}
\+
\textbf{Any name that is not in one of the above scopes \emph{must}
be qualified.}
\+
So you have to write \texttt{self.x} to reference an attribute in
this instance, \texttt{datetime.date} to mean a class defined in module
\texttt{date}, etc.
% \begin{references}
% \url{http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules/292502#292502}
% \end{references}
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, II}
\begin{columns}
\begin{column}[t]{0.6\linewidth}
\begin{lstlisting}
import datetime as dt
def today():
~\HL{td}~ = dt.date.today()
return "today is " + ~\HL{td}~.isoformat()
def hey(~\HL{name}~):
print("Hey " + ~\HL{name}~ + "; " + today())
hey("you")
\end{lstlisting}
\end{column}
\begin{column}[t]{0.4\linewidth}
\raggedleft
Unqualified name within a function: resolves to a local variable.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, III}
\begin{columns}
\begin{column}[t]{0.6\linewidth}
\begin{lstlisting}
import datetime as dt
def today():
td = dt.date.today()
return "today is " + td.isoformat()
def hey(name):
print("Hey " + name + "; " + ~\HL{today}~())
hey("you")
\end{lstlisting}
\end{column}
\begin{column}[t]{0.4\linewidth}
\raggedleft
Unqualified name: since there is no local variable by that name,
it resolves to a module-level binding, i.e., to the
\texttt{today} function defined above.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, IV}
\begin{columns}
\begin{column}[t]{0.6\linewidth}
\begin{lstlisting}
import datetime as ~\HL[Red!25]{dt}~
def today():
td = ~\HL{dt}~.date.today()
return "today is " + td.isoformat()
def hey(name):
print("Hey " + name + "; " + today())
hey("you")
\end{lstlisting}
\end{column}
\begin{column}[t]{0.4\linewidth}
\raggedleft
Unqualified name: resolves to the \texttt{dt} name created at global scope by the \texttt{import} statement.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, V}
\begin{columns}
\begin{column}[t]{0.6\linewidth}
\begin{lstlisting}
import datetime as dt
def today():
td = ~\HL{dt.date}~.today()
return "today is " + td.isoformat()
def hey(name):
print("Hey " + name + "; " + today())
hey("you")
\end{lstlisting}
\end{column}
\begin{column}[t]{0.4\linewidth}
\raggedleft
Qualified name: instructs Python to search the
\texttt{date} attribute within the \texttt{dt} module.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, VI}
\begin{columns}
\begin{column}[t]{0.6\linewidth}
\begin{lstlisting}
import datetime as dt
def today():
td = dt.date.today()
return "today is " + ~\HL{td.isoformat}~()
def hey(name):
print("Hey " + name + "; " + today())
hey("you")
\end{lstlisting}
\end{column}
\begin{column}[t]{0.4\linewidth}
\raggedleft
Qualified name: Python searches the \texttt{isoformat} attribute
within the \texttt{td} object instance.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, VI}
\begin{columns}
\begin{column}[t]{0.6\linewidth}
\begin{lstlisting}
class Vector(object):
def __init__(self, ~\HL[Red!25]{x}~, ~\HL[Red!25]{y}~):
self.x = ~\HL{x}~
self.y = ~\HL{y}~
# ...
\end{lstlisting}
\end{column}
\begin{column}[t]{0.4\linewidth}
\raggedleft
Unqualified name: resolves to a local variable in
scope of function \lstinline|__init__|.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Name resolution rules, VII}
\begin{columns}
\begin{column}[t]{0.6\linewidth}
\begin{lstlisting}
class Vector(object):
def __init__(self, x, y):
~\HL{self.x}~ = x
~\HL{self.y}~ = y
# ...
\end{lstlisting}
\end{column}
\begin{column}[t]{0.4\linewidth}
\raggedleft
Qualified names: resolve to attributes in object \lstinline|self|.
\+ (Actually, \lstinline|self.x = ...| \emph{creates} the
attribute \lstinline|x| on \lstinline|self| if it does not exist
yet.)
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Object initialization}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Vector(object):
"""A 2D Vector."""
~\HL{\textbf{def} \_\_init\_\_(\textbf{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 show(self):
return ("<%g,%g>" % (self.x, self.y))
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
The \lstinline|__init__| method has a special
meaning: it is called when an instance is created.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{Constructors}
The \lstinline|__init__| method is the object constructor.
It should \emph{never} return any value.
\+
You never call \lstinline|__init__| directly, it is invoked by
Python when a new object is created from the class:
\begin{lstlisting}
# calls Vector.\_\_init\_\_
v = Vector(0,1)
\end{lstlisting}
\+
The arguments to \lstinline|__init__| are the arguments you
should supply when creating a class instance.
\+
(Again, minus the \texttt{self} part which is automatically
inserted by Python.)
\end{frame}
% \begin{frame}
% \frametitle{No overloading}
% \textbf{Python does not allow overloading of functions.}
% \+
% Any function.
% \+
% Hence, no overloading of constructors.
% \+
% So: \textbf{a class has one and only one constructor.}
% \end{frame}
\begin{frame}[fragile]
\begin{exercise}
Add a new method \texttt{norm} the \texttt{Vector} class: if
\texttt{v} is an instance of class \texttt{Vector}, then calling
\texttt{v.norm()} returns the norm $\sqrt{v_x^2 + v_y^2}$ of
the associated vector.
(You will need the
\href{http://docs.python.org/2/library/math.html}{math} standard
module for computing square roots.)
\end{exercise}
\+
\begin{exercise}
Add a new method \texttt{unit} to the \texttt{Vector} class: if
\texttt{v} is an instance of class \texttt{Vector}, then calling
\texttt{v.unit()} returns the vector \texttt{u} having the
same direction as \texttt{v} but norm $1$.
\end{exercise}
\end{frame}
\end{document}
%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End: