From 9132e564c5f28f1b10d66d8323ad765f9d914231 Mon Sep 17 00:00:00 2001 From: Prabhu Ramachandran Date: Tue, 15 May 2018 21:27:57 +0530 Subject: Cleanup the numbering for advanced slides. --- advanced_python/01_intro.tex | 62 ++++ advanced_python/02_names_objects.tex | 358 ++++++++++++++++++++ advanced_python/03_varargs_kwargs.tex | 181 ++++++++++ advanced_python/04_only_kwargs.tex | 95 ++++++ advanced_python/05_closures.tex | 105 ++++++ advanced_python/06_practice_functions.tex | 222 +++++++++++++ advanced_python/07_oop_basics.tex | 316 ++++++++++++++++++ advanced_python/08_oop_inheritance.tex | 531 ++++++++++++++++++++++++++++++ advanced_python/09_oop_containership.tex | 207 ++++++++++++ advanced_python/1_intro.tex | 62 ---- advanced_python/2_names_objects.tex | 358 -------------------- advanced_python/3_varargs_kwargs.tex | 181 ---------- advanced_python/4_only_kwargs.tex | 95 ------ advanced_python/5_closures.tex | 105 ------ advanced_python/6_practice_functions.tex | 222 ------------- advanced_python/7_oop_basics.tex | 316 ------------------ advanced_python/8_oop_inheritance.tex | 531 ------------------------------ advanced_python/9_oop_containership.tex | 207 ------------ advanced_python/Makefile | 18 +- 19 files changed, 2086 insertions(+), 2086 deletions(-) create mode 100644 advanced_python/01_intro.tex create mode 100644 advanced_python/02_names_objects.tex create mode 100644 advanced_python/03_varargs_kwargs.tex create mode 100644 advanced_python/04_only_kwargs.tex create mode 100644 advanced_python/05_closures.tex create mode 100644 advanced_python/06_practice_functions.tex create mode 100644 advanced_python/07_oop_basics.tex create mode 100644 advanced_python/08_oop_inheritance.tex create mode 100644 advanced_python/09_oop_containership.tex delete mode 100644 advanced_python/1_intro.tex delete mode 100644 advanced_python/2_names_objects.tex delete mode 100644 advanced_python/3_varargs_kwargs.tex delete mode 100644 advanced_python/4_only_kwargs.tex delete mode 100644 advanced_python/5_closures.tex delete mode 100644 advanced_python/6_practice_functions.tex delete mode 100644 advanced_python/7_oop_basics.tex delete mode 100644 advanced_python/8_oop_inheritance.tex delete mode 100644 advanced_python/9_oop_containership.tex (limited to 'advanced_python') diff --git a/advanced_python/01_intro.tex b/advanced_python/01_intro.tex new file mode 100644 index 0000000..ce75248 --- /dev/null +++ b/advanced_python/01_intro.tex @@ -0,0 +1,62 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[Introduction]{Advanced Python} +\subtitle{Introduction} + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame} + \frametitle{About this material} + \begin{itemize} + \item Covers some ``advanced'' Python material + \item Does not cover all of Python + \item Enough to do many things + \vspace*{0.5in} + \item Learn more yourselves! + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Pre-requisites} + \begin{itemize} + \item Know ``Basic Python programming '' material well + \item Uses Python 3.x exclusively + \item Use any reasonable editor + \begin{itemize} + \item Canopy + \item Spyder + \item Emacs/Vim + \item VS Code \url{code.visualstudio.com} + \end{itemize} + \item Any Python environment works + \begin{itemize} + \item Canopy/EDM + \item Conda/Anaconda + \item Standard Python + \end{itemize} + \item IPython + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Approach and advice} + \begin{itemize} + \item Entirely hands-on (type along!) + \item Many exercises + \item Do not treat this as theory! + \item \alert{Learn by doing!} + \end{itemize} +\end{frame} + +\end{document} diff --git a/advanced_python/02_names_objects.tex b/advanced_python/02_names_objects.tex new file mode 100644 index 0000000..99eb4dd --- /dev/null +++ b/advanced_python/02_names_objects.tex @@ -0,0 +1,358 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + + +\input{macros.tex} + +\title[Names and Objects]{Advanced Python} +\subtitle{Statements, Expressions, Names, and Objects} + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame} + \frametitle{Overview} + \begin{itemize} + \item Statements + \item Expressions + \item Variables + \item Objects + \item Names + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Recap of essential concepts} + \begin{itemize} + \item Mutable data types + \item Immutable data types + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Expressions} + \begin{itemize} + \item Evaluate to something + \item Describe some computation + \item Python evaluates expressions + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Examples of Expressions} + \small + \begin{lstlisting} +In []: 1 +Out[]: 1 + +In []: (1 + 1.2) * 2.0 +Out[]: 4.4 + +In []: sin(0.1) +Out[]: 0.09983341664682815 + +In []: (2 > 1) and (3 > 2) +Out[]: True + +In []: [1, 2, 3, 4][::2] +Out[]: [1, 3] +# Note that each has an output + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Statements} + \begin{itemize} + \item Instruct Python to perform some action + \item A program is a series of statements + \item A statement can have expressions + \item Assignments are statements + \end{itemize} +\begin{lstlisting} +In []: a = 1 + +In []: a += 1 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Assignment statements} + \begin{lstlisting} +In []: a = 1 + +In []: a = 'hello' +\end{lstlisting} +\begin{itemize} +\item These are assignment statements +\item Values are \emph{Objects} +\end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Objects} + \begin{itemize} + \item Objects: all data in Python + \item Have an identity, type, and value + \item Identity is checked using \typ{is} + \item Identity and type cannot change + \item Value of mutables change + \item Immutable object value cannot change + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Names and objects} + \begin{itemize} + \item Assignment binds a name to an object + \end{itemize} + \begin{lstlisting} +In []: a = 1 + +In []: b = 1 + \end{lstlisting} + \begin{itemize} + \item \typ{a} is a name for the object \typ{1} + \item \typ{b} is also a name for the same object \typ{1} + \end{itemize} + \begin{lstlisting} +In []: b = a # The same as above +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Visualizing this} + \begin{minipage}{0.4\textwidth} + \begin{lstlisting} +In []: a = 1 + \end{lstlisting} + \end{minipage} + \begin{minipage}{0.4\textwidth} + \includegraphics[width=2.5in]{data/a_eq_1.png} + \end{minipage} +\pause + \begin{minipage}{0.4\textwidth} + \begin{lstlisting} +In []: b = a + \end{lstlisting} + \end{minipage} + \begin{minipage}{0.4\textwidth} + \includegraphics[width=2.5in]{data/a_b_eq_1.png} + \end{minipage} + + {\small Made with: \url{pythontutor.com}} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Visualizing this ...} + Set \typ{b} to something else: + + \begin{minipage}{0.4\textwidth} + \begin{lstlisting} +In []: a = 1 + +In []: b = 2 + \end{lstlisting} + \end{minipage} + \begin{minipage}{0.4\textwidth} + \includegraphics[width=2.5in]{data/a_1_b_2.png} + \end{minipage} + + \vspace*{1in} + {\small Made with: \url{pythontutor.com}} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Names and objects ...} + \begin{itemize} + \item More interesting when \typ{a} is a list + \end{itemize} + \begin{minipage}{0.4\textwidth} + \begin{lstlisting} +In []: a = [1, 2] +\end{lstlisting} +\end{minipage} + \begin{minipage}{0.4\textwidth} + \hspace*{0.2in}\includegraphics[width=2.25in]{data/a_list_b_2.png} + \end{minipage} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Names and objects ...} + \begin{minipage}{0.4\textwidth} + \begin{lstlisting} +In []: b = a +\end{lstlisting} +\end{minipage} + \begin{minipage}{0.4\textwidth} + \hspace*{0.2in}\includegraphics[width=2.25in]{data/a_b_list.png} + \end{minipage} + \pause + \begin{itemize} + \item \typ{a} is a name for the object \typ{[1, 2]} + \item \typ{b} is also a name for the \alert{same object} + \item Changing the contents of \typ{a} reflect in \typ{b} + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Names and objects ...} + \begin{minipage}{0.4\textwidth} + \begin{lstlisting} +In []: a.append(3) + +In []: b +Out[]: [1, 2, 3] + \end{lstlisting} +\end{minipage} + \begin{minipage}{0.4\textwidth} + \hspace*{0.4in}\includegraphics[width=2.25in]{data/a_b_list1.png} + \end{minipage} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Names and objects ...} + \begin{minipage}{0.4\textwidth} + \begin{itemize} + \item Re-assign \typ{a} + \end{itemize} + \begin{lstlisting} +In []: a = 'hello' +\end{lstlisting} +\pause +\end{minipage} + \begin{minipage}{0.4\textwidth} + \hspace*{0.4in}\includegraphics[width=2.25in]{data/a_str_b_list.png} + \end{minipage} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Names and objects ...} + Rendered more compactly: + \vspace*{0.25in} + \begin{center} + \includegraphics[width=3in]{data/a_str_b_list_compact.png} + \end{center} + \vspace*{0.5in} + {\small Made with: \url{pythontutor.com}} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Expressions: evaluate to something + \item Statements: instruct Python to do something + \item Objects: identity, type, value + \item Assignments bind names to objects + \item Frame: an environment for bindings + \item Explore \url{pythontutor.com} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise 1} + \vspace*{-0.1in} +\begin{lstlisting} +a = [1, 2] +b = a +c = [10, 20] +a.append(c) +del b +c.append(30) +del c +a[-1].append(40) +a = 1 +\end{lstlisting} +\vspace*{0.1in} + \begin{itemize} + \item Run step-by-step on \url{pythontutor.com} + \item Predict the output before you see the answer + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise 2} +\begin{lstlisting} +a = [1, 2] +c = [10, 20] +a.append(c) + +c.append(a) +a.append(a) +\end{lstlisting} +\vspace*{0.1in} + + \begin{itemize} + \item Run step-by-step on \url{pythontutor.com} + \item Predict the output before you see the answer + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise 3} +\begin{lstlisting} +x = [1, 2] +y = 'hello' + +def f(x): + y = x + 1 + return x*y + +f(2) +\end{lstlisting} +\vspace*{0.1in} + \begin{itemize} + \item Run step-by-step on \url{pythontutor.com} + \item Predict the output before you see the answer + \end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise 4} +\begin{lstlisting} +def f(x): + def g(x): + return x + 1 + return g(x) + +f(1) +f(2) +\end{lstlisting} +\vspace*{0.1in} + \begin{itemize} + \item Run step-by-step on \url{pythontutor.com} + \item Predict the output before you see the answer + \end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise 5} +\begin{lstlisting} +def mul(x): + def g(y): + return y*x + return g + +twice = mul(2.0) +twice(20) +\end{lstlisting} +\vspace*{0.1in} + \begin{itemize} + \item Run step-by-step on \url{pythontutor.com} + \item Predict the output before you see the answer + \end{itemize} + +\end{frame} + + +\end{document} diff --git a/advanced_python/03_varargs_kwargs.tex b/advanced_python/03_varargs_kwargs.tex new file mode 100644 index 0000000..29f7e88 --- /dev/null +++ b/advanced_python/03_varargs_kwargs.tex @@ -0,0 +1,181 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[*args, **kw]{Advanced Python} +\subtitle{Arbitrary arguments for functions} + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame} + \frametitle{Overview} + \begin{itemize} + \item Advanced unpacking + \item Variable arguments + \item Arbitrary keyword arguments + \item Unpacking arguments + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Advanced unpacking} + \vspace*{-0.1in} +\begin{lstlisting} +In []: a, b = 1, 2 # We know this! +\end{lstlisting} + \pause + \begin{itemize} + \item In Python 3.x we can also do + \end{itemize} +\begin{lstlisting} +In []: first, *rest = range(5) + +In []: first +Out[]: 0 + +In []: first, *middle, last = range(5) + +In []: middle +Out[]: [1, 2, 3] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Advanced unpacking ...} + \begin{itemize} + \item Also works for files + \end{itemize} +\begin{lstlisting} +In []: f = open('file.txt') + +In []: first, *ign, last = f.readlines() + +In []: f.close() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Arbitrary positional arguments} + \vspace*{-0.1in} + \begin{itemize} + \item Arbitrary positional arguments: \lstinline{*arg} + \end{itemize} + +\begin{lstlisting} +In []: def func(a, b, *args): + ...: print(a, b, args) +\end{lstlisting} +\pause +\begin{lstlisting} +In []: func(1, 2) +1 2 () + +In []: func(1, 2, 'a') +1 2 ('a',) + +In []: func(1, 2, 3, 'a') +1 2 (3, 'a') +\end{lstlisting} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Arbitrary positional arguments} + + Nothing special about \lstinline{args}: + +\begin{lstlisting} +In []: def func(a, b, *rest): + ...: print(a, b, rest) + +\end{lstlisting} +Also is perfectly valid +\end{frame} + +\begin{frame}[fragile] + \frametitle{Arbitrary keyword arguments} + \vspace*{-0.1in} + \begin{itemize} + \item Keyword arguments using \lstinline{**kw} + \end{itemize} +\begin{lstlisting} +In []: def func(a, b='b', **kw): + ...: print(a, b, kw) +\end{lstlisting} + \pause +\begin{lstlisting} +In []: func(1) +1 b {} + +In []: func(1, 2) +1 2 {} + +In []: func(1, b=2) +1 2 {} +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Arbitrary keyword arguments} +\begin{lstlisting} +In []: def func(a, b='b', **k): + ...: print(a, b, k) + +In []: func(1, c=3) +1 b {'c': 3} + +In []: func(1, c=3, d=4) +1 b {'c': 3, 'd': 4} +\end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Argument unpacking} +\begin{lstlisting} +In []: def func(a, b): + ...: print(a, b) + +In []: func(*[5, 10]) +5 10 + +In []: func(*(5, 10)) +5 10 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Argument unpacking ...} +\begin{lstlisting} +In []: def func(a=1, b=2): + ...: print(a, b) + +In []: func(**{'a':5, 'b':10}) +5 10 + +In []: func(**dict(a=5, b=10)) +5 10 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Summary} + \begin{itemize} + \item Advanced unpacking + \item Arbitrary positional arguments with \lstinline{*args} + \item Arbitrary keyword arguments with \lstinline{**kw} + \item Argument unpacking + \end{itemize} +\end{frame} + + +\end{document} diff --git a/advanced_python/04_only_kwargs.tex b/advanced_python/04_only_kwargs.tex new file mode 100644 index 0000000..8d4caef --- /dev/null +++ b/advanced_python/04_only_kwargs.tex @@ -0,0 +1,95 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[only kwargs]{Advanced Python} +\subtitle{Keyword-only arguments} + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame}[fragile, plain] + \frametitle{Motivation} + \vspace*{-0.1in} + \begin{itemize} + \item One can mix positional and keyword arguments + \end{itemize} + \begin{lstlisting} +In []: def f(a, b=2): + ...: print(a, b) + +In []: f(a=2, b=3) +2 3 + +In []: f(b=2, a=3) +3 2 + +In []: f(10, 20) +1 2 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Motivation} + \begin{itemize} + \item Function changes: positional arguments change in order or number + \item Accidentally passing an extra argument + \item Can we have purely keyword arguments? + + \vspace*{0.5in} + \item Yes, in Python 3.x! + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Keyword-only arguments} + \begin{lstlisting} +In []: def f(a, *args, b=False): + ...: print(a, args, b) + +In []: f(1, 20) +1 (20,) False + +In []: f(1, b=20) +1 () 20 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Keyword-only arguments} + \noindent Without any extra arguments: +\vspace*{0.25in} + \begin{lstlisting} +In []: def f(a, *, b=False): + ...: print(a, b) + +In []: f(1, 20) +TypeError: f() takes 1 positional arg... +\end{lstlisting} +\pause + \begin{lstlisting} +In []: f(1, b=20) +1 20 + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Discussion} + \begin{itemize} + \item Solves the problem nicely + \item \typ{b}: can only be specified as keyword argument + + \item Cannot be called as a positional argument + \end{itemize} +\end{frame} + + +\end{document} diff --git a/advanced_python/05_closures.tex b/advanced_python/05_closures.tex new file mode 100644 index 0000000..f3571ef --- /dev/null +++ b/advanced_python/05_closures.tex @@ -0,0 +1,105 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[Closures]{Advanced Python} +\subtitle{Closures} + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame} + \frametitle{Overview} + \begin{itemize} + \item Higher-order functions + \item Closures + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Recap of higher-order functions} + \begin{lstlisting} +In []: def sqr(x): + ...: return x*x + +In []: def sum(func, n): + ...: result = 0 + ...: for i in range(n): + ...: result += func(i) + ...: return result + +In []: sum(sqr, 5) +Out[]: 30 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Recap of higher-order functions} + \begin{lstlisting} +def f(): + def g(x): + return x+1 + return g + +In []: func = f() +In []: func(1) +In []: f()(1) # Also valid! + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Closures} + \begin{lstlisting} +def mul(x): + def g(y): + return y*x + return g + +In []: twice = mul(2.0) +In []: twice(20) +Out[]: 40.0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Closures ...} + \begin{lstlisting} + +In []: thrice = mul(3.0) +In []: thrice(20) +Out[]: 60.0 + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Discussion} + \begin{itemize} + \item \typ{g} uses \typ{x} + \item \typ{x} is different in each case + \item So \typ{twice, thrice} ``curry'' the passed \typ{x} + \item This function is called a closure + \item Encloses its local environment + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Summary: Higher-order functions} + \begin{itemize} + \item Functions that manipulate functions + \item Passing a function as an argument + \item A function that returns another function + \item A closure + \end{itemize} +\end{frame} + +\end{document} diff --git a/advanced_python/06_practice_functions.tex b/advanced_python/06_practice_functions.tex new file mode 100644 index 0000000..ce7c9d6 --- /dev/null +++ b/advanced_python/06_practice_functions.tex @@ -0,0 +1,222 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[Practice advanced functions]{Advanced Python} +\subtitle{Practice advanced functions} + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: product of all arguments} + \begin{block}{} + Write a function called \lstinline{prod} that can be called with any + number of arguments (at least one) but computes the product of all the + given values as seen below. + \end{block} + +\begin{lstlisting} +In []: prod(2., 2.) +Out[]: 4.0 + +In []: prod(1, 2, 3) +Out[]: 6 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +def prod(*args): + res = 1.0 + for x in args: + res *= x + return res + +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Another solution} +\begin{lstlisting} +def prod(*args): + res = args[0] + for i in range(1, len(args)): + res *= args[i] + return res + +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Exercise: function applied to arguments} + \begin{block}{} + Write a function called \lstinline{apply} which takes a function followed + by an arbitrary number of arguments and returns a list with the function + applied to all the arguments as shown below. + \end{block} + +\begin{lstlisting} +In []: def twice(x): + ...: return x*2 + +In []: apply(twice, 1, 2) +Out[]: [2, 4] + +In []: apply(twice, 1, 2, 3) +Out[]: [2, 4, 6] + +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +def apply(f, *args): + result = [] + for arg in args: + result.append(f(arg)) + return result +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: number of kwargs} + \begin{block}{} + Write a function \lstinline{nkw} that takes an arbitrary number of + keyword arguments and returns the number of keyword arguments passed. + \end{block} + +\begin{lstlisting} +In []: nkw(x=1, y=2) +Out[]: 2 + +In []: nkw() +Out[]: 0 + +In []: nkw(x=1) +Out[]: 1 +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +def nkw(**kw): + return len(kw) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: name of kwargs} + \begin{block}{} + Write a function \lstinline{kwname} that takes an arbitrary number of + keyword arguments and returns a sorted list of the keyword arguments + passed. + \end{block} + +\begin{lstlisting} +In []: kwname(x=1, y=2) +Out[]: ['x', 'y'] + +In []: kwname() +Out[]: [] + +In []: kwname(z=1, a=2) +Out[]: ['a', 'z'] +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +def kwname(**kw): + return sorted(kw.keys()) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: power function} + \begin{block}{} + Write a function called \lstinline{power} that is given a single integer + and returns a function that takes a single number but returns its power. + For example: + \end{block} + +\begin{lstlisting} +In []: pow2 = power(2) +In []: pow2(2) +Out[]: 4 +In []: pow2(4) +Out[]: 16 + +In []: pow3 = power(3) +In []: pow3(2) +Out[]: 8 +\end{lstlisting} + Hint: this is a closure. +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +def power(n): + def g(x): + return x**n + return g + +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Exercise: debug function} + \begin{block}{} + Write a function called \lstinline{debug} that takes any function as a + single positional argument but returns a function that first prints out + the arguments passed to the function before calling it and returning its + value. For example: + \end{block} + +\begin{lstlisting} +In []: debug(max)(1, 2) +(1, 2) {} +Out[]: 2 + +In []: import math + +In []: debug(math.sin)(1.0) +(1.0,) {} +Out[]: 0.8414709848078965 + +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +def debug(f): + def g(*args, **kw): + print(args, kw) + return f(*args, **kw) + return g +\end{lstlisting} +\end{frame} + + +\end{document} diff --git a/advanced_python/07_oop_basics.tex b/advanced_python/07_oop_basics.tex new file mode 100644 index 0000000..d6f4e24 --- /dev/null +++ b/advanced_python/07_oop_basics.tex @@ -0,0 +1,316 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[Introduction to OOP]{Advanced Python} +\subtitle{Introduction to Object Oriented Programming } + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame} + \frametitle{Background and caveats} + \begin{itemize} + \item You don't need OOP for everything! + \item Helps with larger programs + \item Appreciate it, when you write more code + \item Very useful to organize/modularize your code + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{What are the benefits?} + \begin{itemize} + \item Create new data types + \item Create objects to simulate a real problem + \item Makes problem solving more natural and elegant + \item Can be easier to understand + \item Allows for code-reuse + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Example: Managing Talks} + \begin{itemize} + \item Want to manage list of talks at a conference + \end{itemize} + \begin{lstlisting} +talk = {'Speaker': 'Guido van Rossum', + 'Title': 'The History of Python' + 'Tags': 'python,history,C,advanced'} + +def get_first_name(talk): + return talk['Speaker'].split()[0] + +def get_tags(talk): + return talk['Tags'].split(',') + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Issues} + \begin{itemize} + \item Not convenient to handle large number of talks + \item Data separate from functions to manipulate talk + \item Must pass \lstinline{talk} to each function + \item No clear organization + \item What if we had different kinds of talks? + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Creating a \typ{class}} + \begin{lstlisting} +class Talk: + """A class for the Talks.""" + def __init__(self, speaker, title, tags): + self.speaker = speaker + self.title = title + self.tags = tags + \end{lstlisting} + \begin{itemize} + \item \lstinline{class} is a keyword + \item \lstinline{Talk} is the name of the class + \item Notice the class doc-string + \item Notice the indentation + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{methods and \lstinline{self}} + \begin{lstlisting} +class Talk: + # ... + def get_speaker_firstname(self): + return self.speaker.split()[0] + + def get_tags(self): + return self.tags.split(',') + \end{lstlisting} + \begin{itemize} + \item \lstinline{self} is a reference to the object itself + \item The name \lstinline{self} is a convention + \item Instance variables: \lstinline{self.name} + \end{itemize} +\end{frame} + +\begin{frame}[fragile, plain] + \frametitle{Exercise: type this out} + \vspace*{-0.1in} + \begin{lstlisting} +class Talk: + """A class for the Talks.""" + def __init__(self, speaker, title, tags): + self.speaker = speaker + self.title = title + self.tags = tags + + def get_speaker_firstname(self): + return self.speaker.split()[0] + + def get_tags(self): + return self.tags.split(',') + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Instantiating a class to create objects} + \begin{itemize} + \item Creating objects or instances of a class is simple + \item Call class, with arguments required by \lstinline{__init__} + \end{itemize} + \begin{lstlisting} +In []: bdfl = Talk('Guido van Rossum', + ...: 'The History of Python', + ...: 'python,history,C,advanced') + \end{lstlisting} + \begin{itemize} + \item We can now call the methods of the Class + \end{itemize} + \begin{lstlisting} +In []: bdfl.get_tags() +In []: bdfl.get_speaker_firstname() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\lstinline{__init__} method} + \begin{itemize} + \item A special method + \item Called every time an instance of the class is created + \end{itemize} + \begin{lstlisting} +In []: print(bdfl.speaker) +In []: print(bdfl.tags) +In []: print(bdfl.title) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Creating more instances} + \begin{lstlisting} +In []: talk = Talk('Arun K', + ...: 'Python in biosciences', 'python,bio') +In []: talk.get_tags() +In []: talk.tags + +In []: type(talk) +Out[]: __main__.Talk +In []: type(bdfl) +\end{lstlisting} +\begin{itemize} +\item Note that \lstinline{talk} and \lstinline{bdfl} are different objects +\item Different values but same type +\item \lstinline{Talk} \alert{encapsulates} the data and behavior of a talk +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Changing/adding attributes} +\begin{lstlisting} +In []: talk.speaker = 'Arun K P' + +In []: talk.tags = 'python,bioscience' +\end{lstlisting} +\pause +\begin{lstlisting} +# Adding attributes + +In []: talk.x = 1 + +In []: talk.y = 'hello' +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Introduction to Object Oriented Programming + \item A simple example + \item Defining a \lstinline{class} + \item Methods and attributes: encapsulation + \item Changing/adding attributes + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise: simplest class} + \begin{block}{} + Create the simplest possible class, called \lstinline{Simple}, which has + no attributes or methods. Try this out on your own IPython interpreters. + You should be able to instantiate it as follows: + \end{block} +\begin{lstlisting} +In []: s = Simple() +\end{lstlisting} + \pause + \begin{block}{Hint} + Remember the \lstinline{pass} statement? + \end{block} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Simple: + pass +\end{lstlisting} + \vspace*{0.5in} + + That is all! +\end{frame} + +\begin{frame}[fragile,plain, fragile] + \frametitle{Exercise: \lstinline{Person} class 1} + \begin{block}{} + Create a simple \lstinline{Person} class with two attributes: a + \lstinline{name} (a string) and an \lstinline{age} (a float). To be used + as follows: + \end{block} +\begin{lstlisting} +In []: p = Person('Arun', 22.0) +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Person: + def __init__(self, name, age): + self.name = name + self.age = age +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: \lstinline{Person} class 2} + \begin{block}{} + Create a simple \lstinline{Person} class with two attributes a + \lstinline{name} and an \lstinline{age}. However, let the name default to + the string \lstinline{'name'} and the age default to 0.0. + \end{block} +\begin{lstlisting} +In []: p = Person() +In []: print(p.name, p.age) +name 0.0 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Person: + def __init__(self, name='name', age=0.0): + self.name = name + self.age = age +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain, fragile] + \frametitle{Exercise: simple method} + \begin{block}{} + Create a simple \lstinline{Person} class with two attributes as before. + Add a method called \lstinline{birthday} which takes no arguments and + which prints \lstinline{'HBD '} and also increases the age by 1. + Note that \lstinline{} is the name of the instance. + \end{block} + +\begin{lstlisting} +In []: p = Person(name='Ram') +In []: p.birthday() +HBD Ram +In []: p.age +Out[]: 1.0 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Person: + def __init__(self, name='name', age=0.0): + self.name = name + self.age = age + + def birthday(self): + print('HBD', self.name) + self.age += 1.0 +\end{lstlisting} +\end{frame} + + + +\end{document} diff --git a/advanced_python/08_oop_inheritance.tex b/advanced_python/08_oop_inheritance.tex new file mode 100644 index 0000000..657dfad --- /dev/null +++ b/advanced_python/08_oop_inheritance.tex @@ -0,0 +1,531 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[OOP Inheritance]{Advanced Python} +\subtitle{Object Oriented Programming: Inheritance} + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame} + \frametitle{Recap} + \begin{itemize} + \item Created a new \lstinline{Talk} class + \item Puts together data and methods + \item Can make instances of the class + \item Each instance has its own data + \item Objects encapsulate data and behavior + \end{itemize} +\end{frame} + +\begin{frame}[fragile, plain] + \frametitle{Recap: the Talk class} + \vspace*{-0.1in} + \begin{lstlisting} +class Talk: + """A class for the Talks.""" + def __init__(self, speaker, title, tags): + self.speaker = speaker + self.title = title + self.tags = tags + + def get_speaker_firstname(self): + return self.speaker.split()[0] + + def get_tags(self): + return self.tags.split(',') + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Instantiating a class to create objects} + \begin{lstlisting} +In []: bdfl = Talk('Guido van Rossum', + ...: 'The History of Python', + ...: 'python,history,C,advanced') +In []: bdfl.get_tags() +In []: bdfl.get_speaker_firstname() +In []: bdfl.tags + +In []: type(bdfl) + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Classes: the big picture} + \begin{itemize} + \item Lets you create new data types + \item Class is a template for an object belonging to that class + \item Instantiating a class creates an instance (an object) + \item An instance encapsulates the state (data) and behavior + (methods) + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Objects and Methods} + \begin{itemize} + \item Objects group data with functions + \item Everything in Python is an object + \item Strings, lists, functions and even modules + \end{itemize} + \begin{lstlisting} + s = "Hello World" + s.lower() + + l = [1, 2, 3, 4, 5] + l.append(6) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes} + \begin{lstlisting} +In []: s = "Hello World" +In []: type(s) + \end{lstlisting} + \begin{itemize} + \item A new string, comes along with methods + \item A template or a blue-print, where these definitions lie + \item This blue print for building objects is called a + \lstinline{class} + \item \lstinline{s} is an object of the \lstinline{str} class + \item An object is an ``instance'' of a class + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Classes: inheritance} + \begin{itemize} + \item Allows you to define an inheritance hierarchy + \begin{itemize} + \item ``A Honda car \alert{is a} car.'' + \item ``A car \alert{is an} automobile.'' + \item ``A Python \alert{is a} reptile.'' + \end{itemize} + \item All data/behavior of a car should be there in a ``Honda'' car + \item All data/behavior associated with a reptile ought to inhere in a snake + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Inheritance} + \vspace*{-0.1in} + \begin{itemize} + \item Suppose, we wish to write a \lstinline{Tutorial} class + \item It's almost same as \lstinline{Talk} except for minor differences + \item We can ``inherit'' from \lstinline{Talk} + \end{itemize} + \pause + \begin{lstlisting} +class Tutorial(Talk): + """A class for the tutorials.""" + def __init__(self, speaker, title, tags, + needs_computer=True): + super().__init__(speaker, title, tags) + self.needs_computer = needs_computer + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Inheritance} + \vspace*{-0.1in} + \begin{itemize} + \item Modified \lstinline{__init__} method + \item Inherits: \lstinline{get_tags} and + \lstinline{get_speaker_firstname} + \end{itemize} + \begin{lstlisting} +tut = Tutorial('Travis Oliphant', + 'Numpy Basics', + 'numpy,python,beginner') +tut.get_speaker_firstname() +tut.needs_computer + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Some points} + \begin{itemize} + \item \lstinline{Tutorial} is a subclass (or child) of \lstinline{Talk} + \item \lstinline{Tutorial} is derived from (inherits from) \lstinline{Talk} + \item \lstinline{Talk} is the base class (or parent class) + \item Only the \lstinline{__init__} has been changed + \item This is called overriding + \item \lstinline{super} ensures that the parent class is called + \item Calling the parent is not automatic + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise: try this} +\begin{lstlisting} +class Tutorial(Talk): + def __init__(self, speaker, title, tags, + needs_computer=True): + self.needs_computer = needs_computer + +In []: t = Tutorial('G v R', 'Python', 'py,tut') + +In []: t.needs_computer + +In []: t.speaker + +In []: t.get_speaker_firstname() + +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Inheritance} + \begin{itemize} + \item A \lstinline{Tutorial} is a \lstinline{Talk} + \item A \lstinline{Talk} is not a \lstinline{Tutorial} + \item The sentence above should make sense! + \item A \lstinline{Cat} is an \lstinline{Animal} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Incorrect inheritance} + \begin{itemize} + \item A \lstinline{Talk} is a \lstinline{Speaker} or + \item A \lstinline{Speaker} is a \lstinline{Room} + \item Something is wrong in your OO design! + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Summary} + \begin{itemize} + \item Inheritance + \item The importance of making sense + \item The \lstinline{super} function + \end{itemize} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Exercises + +\begin{frame}[fragile] + \frametitle{Exercise: \lstinline{Animal} class} + \begin{block}{} + Create an \lstinline{Animal} class that has a name attribute (str) and a + single method called \lstinline{greet} which takes no arguments but returns + a string about how the animal makes a greeting. By default let + \lstinline{greet} return \lstinline{' says greet'}. + \end{block} +\begin{lstlisting} +In []: a = Animal('human') +In []: a.greet() +Out[]: 'human says greet' +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Animal: + def __init__(self, name): + self.name = name + def greet(self): + return self.name + ' says greet' +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Solution} + \begin{itemize} + \item Note that this is the same as + \end{itemize} +\begin{lstlisting} +class Animal(object): + # ... +\end{lstlisting} + \begin{itemize} + \item Otherwise \lstinline{object} is implicitly the base class + \end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise: \lstinline{Cat} class} + \begin{block}{} + Create a \lstinline{Cat} class which derives from the \lstinline{Animal} + class \alert{override} \lstinline{greet} return + \lstinline{' says meow'}. + \end{block} +\begin{lstlisting} +In []: a = Cat('Felix') +In []: a.greet() +Out[]: 'Felix says meow' +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Animal: + def __init__(self, name): + self.name = name + def greet(self): + return self.name + ' says greet' + +class Cat(Animal): + def greet(self): + return self.name + ' says meow' +\end{lstlisting} + \begin{itemize} + \item Note, no need to override \lstinline{__init__} + \end{itemize} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Observation: order matters} +\begin{lstlisting} +class Cat(Animal): + def greet(self): + return self.name + ' says meow' + +class Animal: + def __init__(self, name): + self.name = name + def greet(self): + return self.name + ' says greet' + +\end{lstlisting} + \begin{itemize} + \item Will the above code work? Explore this and see what error you get. + \end{itemize} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Exercise: \lstinline{Mammal} class} + \begin{block}{} + Create a \lstinline{Mammal} class that derives from \lstinline{Animal} + that takes an additional argument specifying the number of legs (an + integer) and stores it in the attribute \lstinline{legs}. + \end{block} + +\begin{lstlisting} +In []: m = Mammal('dog', 4) +In []: m.legs +Out[]: 4 +In []: m.greet() +Out[]: 'dog says greet' +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Mammal(Animal): + def __init__(self, name, legs): + super().__init__(name) + self.legs = legs +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution alternative} +\begin{lstlisting} +class Mammal(Animal): + def __init__(self, name, legs): + self.name = name + self.legs = legs +\end{lstlisting} + \begin{itemize} + \item Will also work but a \alert{bad} idea + \item What if \lstinline{Animal.__init__} changes? + \end{itemize} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{More on \typ{super}} +We can also do: +\begin{lstlisting} +class Mammal(Animal): + def __init__(self, name, legs): + super(Mammal, self).__init__(name) + +In []: super? + +In []: m = Mammal('dog', 4) +In []: super(Mammal, m) + +In []: super(Mammal, m).greet() + +In []: super(Animal, m).greet() # ?? +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Exercise: \lstinline{Human} class} + \begin{block}{} + Create a \lstinline{Human} class that derives from \lstinline{Mammal} + modify its \lstinline{greet} method to return + \lstinline{' says hello'}. Also change the default number of legs + to 2. + \end{block} + +\begin{lstlisting} +In []: h = Human('Ram') +In []: h.legs +Out[]: 2 +In []: h.greet() +Out[]: 'Ram says hello' +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Human(Mammal): + def __init__(self, name, legs=2): + super().__init__(name, legs) + def greet(self): + return self.name + ' says hello' +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Complete Solution} + \vspace*{-0.1in} + \small +\begin{lstlisting} +class Animal: + def __init__(self, name): + self.name = name + def greet(self): + return self.name + ' says greet' + +class Mammal(Animal): + def __init__(self, name, legs): + super().__init__(name) + self.legs = legs + +class Human(Mammal): + def __init__(self, name, legs=2): + super().__init__(name, legs) + def greet(self): + return self.name + ' says hello' +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Observations} + \begin{itemize} + \item \py{Human} is a \py{Mammal} + \item \py{Human} is an \py{Animal} + \end{itemize} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Exercise: Methods in subclass} + \begin{block}{} + Add a method to \py{Human} called \py{speak} which prints + \py{'My name is '}. + \end{block} + +\begin{lstlisting} +In []: h = Human('Ram') +In []: h.speak() +My name is Ram +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Human(Mammal): + def __init__(self, name, legs=2): + super().__init__(name, legs) + def greet(self): + return self.name + ' says hello' + def speak(self): + print('My name is', self.name) +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Observations} + \begin{itemize} + \item \py{Human} is a \py{Mammal} + \item \py{Human} is an \py{Animal} + \item \py{Human} can speak but \py{Mammal, Animal} cannot + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exercise: class in a module} + + \begin{block}{} + Put the \py{Animal, Mammal, Human} classes inside a Python file, called + \texttt{oop.py} somewhere convenient in your computer. Add the following + code at the bottom. + \end{block} +\begin{lstlisting} +print(__name__) +h = Human('Sam') +print(h.greet()) +print(h.legs) +print(type(h)) +\end{lstlisting} + + \begin{itemize} + \item Execute this module using \texttt{python oop.py} + \item Import the \py{Human} class from IPython + \end{itemize} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: overriding a \typ{list} method} + \begin{block}{} + Create a subclass of the standard Python \py{list} called \py{MyList} and + override just the \py{append} method to print the item appended as + \py{'appending '} and then call the parent append so as to + internally append the item. The usage should be as follows: + \end{block} + +\begin{lstlisting} +In []: l = MyList() +In []: l.append(1) +appending 1 +In []: l +Out[]: [1] +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class MyList(list): + def append(self, item): + print('appending', item) + super().append(item) +\end{lstlisting} +\end{frame} + + + +\end{document} diff --git a/advanced_python/09_oop_containership.tex b/advanced_python/09_oop_containership.tex new file mode 100644 index 0000000..6434819 --- /dev/null +++ b/advanced_python/09_oop_containership.tex @@ -0,0 +1,207 @@ +\documentclass[14pt,compress,aspectratio=169]{beamer} + +\input{macros.tex} + +\title[OOP containership]{Advanced Python} +\subtitle{Object Oriented Programming: containership } + +\author[FOSSEE] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} + +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame} + \frametitle{Recap} + \begin{itemize} + \item Created \lstinline{Talk} and \lstinline{Tutorial} classes + \item Know how to create objects: instantiation of a class + \vspace*{0.5in} + + \item Let us create a conference! + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Conference class} + \vspace*{-0.1in} +\begin{lstlisting} +class Conference: + def __init__(self, talks=None): + if talks is None: + talks = [] + self.talks = talks + + def add_talk(self, talk): + self.talks.append(talk) + + def schedule(self): + for talk in self.talks: + print(talk.speaker, talk.title) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Using this} +\begin{lstlisting} +In []: c = Conference() + +In []: t = Talk('Guido', 'Python4', 'py,core') + +In []: c.add_talk(t) + +In []: c.schedule() + +\end{lstlisting} + \begin{itemize} + \item Easy to read + \item Nicely split up + \item Reflects the real world + + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{But why not this?} +\begin{lstlisting} +class Conference: + def __init__(self, talks=[]): + self.talks = talks +\end{lstlisting} + \begin{itemize} + \item Easier + \item Less code + \item Let's try it! + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Gotcha!} +\begin{lstlisting} +In []: c1 = Conference() +In []: c1.add_talk(1) +In []: c1.talks + +In []: c2 = Conference() +In []: c2.talks + +\end{lstlisting} + + \begin{itemize} + \item What is going on? + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Beware of mutable default arguments!} + \begin{itemize} + \item Default arguments are evaluated once + \item When the method/function is defined + \item So, if the object is mutable we have a problem + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Which is why we have this} +\begin{lstlisting} +class Conference: + def __init__(self, talks=None): + if talks is None: + talks = [] + self.talks = talks +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Containership} + \begin{itemize} + \item \lstinline{Conference} class manages all the talks + \item It contains the talks and tutorials + \item Allows us to build complexity by \alert{composition} + \item Hierarchical organization + \item Allows us to mirror the real objects in code + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Some more examples} + \begin{itemize} + \item OOP for a \lstinline{Company} + \item OOP for a \lstinline{Bank} + \item OOP for a \lstinline{School} or \lstinline{College} + \item OOP for a cell phone, computer, ... + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Design guidelines} + \begin{itemize} + \item Important to make sense + \item Should be easy to explain the relationships and responsibilities of + each class + \item Inheritance should ``read'' correctly and make sense + \item No object should be too responsible + \item Functionality should be suitably delegated + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Creating a more complex class + \item Containing other objects + \item Issue with mutable default arguments + \item Important design guidelines + \end{itemize} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: Create a Zoo} + \begin{block}{} + Create a \py{Zoo} class which allows someone to add any number of animals. + This means it should work for \py{Animal, Mammal, Human} objects. It + should have a single \py{greet} method which calls the greet method of all + of the animals it has and prints that: + \end{block} + +\begin{lstlisting} +In []: b = Animal('crow') +In []: m = Mammal('dog', legs=4) +In []: h = Human('Abhinav') +In []: z = Zoo(b, m, h) +In []: z.greet() +crow says greet +dog says greet +Abhinav says hello +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain, fragile] + \frametitle{Solution} +\begin{lstlisting} +class Zoo: + def __init__(self, *animals): + self.animals = list(animals) + + def greet(self): + for animal in self.animals: + print(animal.greet()) +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Observations} + \begin{itemize} + \item Notice the abstraction of \py{Animal} + \item The \py{Zoo} will work with any object that has the \py{greet} method + \item That is, any \py{Animal} + \end{itemize} +\end{frame} + +\end{document} diff --git a/advanced_python/1_intro.tex b/advanced_python/1_intro.tex deleted file mode 100644 index ce75248..0000000 --- a/advanced_python/1_intro.tex +++ /dev/null @@ -1,62 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[Introduction]{Advanced Python} -\subtitle{Introduction} - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame} - \frametitle{About this material} - \begin{itemize} - \item Covers some ``advanced'' Python material - \item Does not cover all of Python - \item Enough to do many things - \vspace*{0.5in} - \item Learn more yourselves! - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Pre-requisites} - \begin{itemize} - \item Know ``Basic Python programming '' material well - \item Uses Python 3.x exclusively - \item Use any reasonable editor - \begin{itemize} - \item Canopy - \item Spyder - \item Emacs/Vim - \item VS Code \url{code.visualstudio.com} - \end{itemize} - \item Any Python environment works - \begin{itemize} - \item Canopy/EDM - \item Conda/Anaconda - \item Standard Python - \end{itemize} - \item IPython - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Approach and advice} - \begin{itemize} - \item Entirely hands-on (type along!) - \item Many exercises - \item Do not treat this as theory! - \item \alert{Learn by doing!} - \end{itemize} -\end{frame} - -\end{document} diff --git a/advanced_python/2_names_objects.tex b/advanced_python/2_names_objects.tex deleted file mode 100644 index 99eb4dd..0000000 --- a/advanced_python/2_names_objects.tex +++ /dev/null @@ -1,358 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - - -\input{macros.tex} - -\title[Names and Objects]{Advanced Python} -\subtitle{Statements, Expressions, Names, and Objects} - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame} - \frametitle{Overview} - \begin{itemize} - \item Statements - \item Expressions - \item Variables - \item Objects - \item Names - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Recap of essential concepts} - \begin{itemize} - \item Mutable data types - \item Immutable data types - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Expressions} - \begin{itemize} - \item Evaluate to something - \item Describe some computation - \item Python evaluates expressions - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Examples of Expressions} - \small - \begin{lstlisting} -In []: 1 -Out[]: 1 - -In []: (1 + 1.2) * 2.0 -Out[]: 4.4 - -In []: sin(0.1) -Out[]: 0.09983341664682815 - -In []: (2 > 1) and (3 > 2) -Out[]: True - -In []: [1, 2, 3, 4][::2] -Out[]: [1, 3] -# Note that each has an output - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Statements} - \begin{itemize} - \item Instruct Python to perform some action - \item A program is a series of statements - \item A statement can have expressions - \item Assignments are statements - \end{itemize} -\begin{lstlisting} -In []: a = 1 - -In []: a += 1 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Assignment statements} - \begin{lstlisting} -In []: a = 1 - -In []: a = 'hello' -\end{lstlisting} -\begin{itemize} -\item These are assignment statements -\item Values are \emph{Objects} -\end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Objects} - \begin{itemize} - \item Objects: all data in Python - \item Have an identity, type, and value - \item Identity is checked using \typ{is} - \item Identity and type cannot change - \item Value of mutables change - \item Immutable object value cannot change - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Names and objects} - \begin{itemize} - \item Assignment binds a name to an object - \end{itemize} - \begin{lstlisting} -In []: a = 1 - -In []: b = 1 - \end{lstlisting} - \begin{itemize} - \item \typ{a} is a name for the object \typ{1} - \item \typ{b} is also a name for the same object \typ{1} - \end{itemize} - \begin{lstlisting} -In []: b = a # The same as above -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Visualizing this} - \begin{minipage}{0.4\textwidth} - \begin{lstlisting} -In []: a = 1 - \end{lstlisting} - \end{minipage} - \begin{minipage}{0.4\textwidth} - \includegraphics[width=2.5in]{data/a_eq_1.png} - \end{minipage} -\pause - \begin{minipage}{0.4\textwidth} - \begin{lstlisting} -In []: b = a - \end{lstlisting} - \end{minipage} - \begin{minipage}{0.4\textwidth} - \includegraphics[width=2.5in]{data/a_b_eq_1.png} - \end{minipage} - - {\small Made with: \url{pythontutor.com}} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Visualizing this ...} - Set \typ{b} to something else: - - \begin{minipage}{0.4\textwidth} - \begin{lstlisting} -In []: a = 1 - -In []: b = 2 - \end{lstlisting} - \end{minipage} - \begin{minipage}{0.4\textwidth} - \includegraphics[width=2.5in]{data/a_1_b_2.png} - \end{minipage} - - \vspace*{1in} - {\small Made with: \url{pythontutor.com}} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Names and objects ...} - \begin{itemize} - \item More interesting when \typ{a} is a list - \end{itemize} - \begin{minipage}{0.4\textwidth} - \begin{lstlisting} -In []: a = [1, 2] -\end{lstlisting} -\end{minipage} - \begin{minipage}{0.4\textwidth} - \hspace*{0.2in}\includegraphics[width=2.25in]{data/a_list_b_2.png} - \end{minipage} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Names and objects ...} - \begin{minipage}{0.4\textwidth} - \begin{lstlisting} -In []: b = a -\end{lstlisting} -\end{minipage} - \begin{minipage}{0.4\textwidth} - \hspace*{0.2in}\includegraphics[width=2.25in]{data/a_b_list.png} - \end{minipage} - \pause - \begin{itemize} - \item \typ{a} is a name for the object \typ{[1, 2]} - \item \typ{b} is also a name for the \alert{same object} - \item Changing the contents of \typ{a} reflect in \typ{b} - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Names and objects ...} - \begin{minipage}{0.4\textwidth} - \begin{lstlisting} -In []: a.append(3) - -In []: b -Out[]: [1, 2, 3] - \end{lstlisting} -\end{minipage} - \begin{minipage}{0.4\textwidth} - \hspace*{0.4in}\includegraphics[width=2.25in]{data/a_b_list1.png} - \end{minipage} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Names and objects ...} - \begin{minipage}{0.4\textwidth} - \begin{itemize} - \item Re-assign \typ{a} - \end{itemize} - \begin{lstlisting} -In []: a = 'hello' -\end{lstlisting} -\pause -\end{minipage} - \begin{minipage}{0.4\textwidth} - \hspace*{0.4in}\includegraphics[width=2.25in]{data/a_str_b_list.png} - \end{minipage} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Names and objects ...} - Rendered more compactly: - \vspace*{0.25in} - \begin{center} - \includegraphics[width=3in]{data/a_str_b_list_compact.png} - \end{center} - \vspace*{0.5in} - {\small Made with: \url{pythontutor.com}} -\end{frame} - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item Expressions: evaluate to something - \item Statements: instruct Python to do something - \item Objects: identity, type, value - \item Assignments bind names to objects - \item Frame: an environment for bindings - \item Explore \url{pythontutor.com} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise 1} - \vspace*{-0.1in} -\begin{lstlisting} -a = [1, 2] -b = a -c = [10, 20] -a.append(c) -del b -c.append(30) -del c -a[-1].append(40) -a = 1 -\end{lstlisting} -\vspace*{0.1in} - \begin{itemize} - \item Run step-by-step on \url{pythontutor.com} - \item Predict the output before you see the answer - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise 2} -\begin{lstlisting} -a = [1, 2] -c = [10, 20] -a.append(c) - -c.append(a) -a.append(a) -\end{lstlisting} -\vspace*{0.1in} - - \begin{itemize} - \item Run step-by-step on \url{pythontutor.com} - \item Predict the output before you see the answer - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise 3} -\begin{lstlisting} -x = [1, 2] -y = 'hello' - -def f(x): - y = x + 1 - return x*y - -f(2) -\end{lstlisting} -\vspace*{0.1in} - \begin{itemize} - \item Run step-by-step on \url{pythontutor.com} - \item Predict the output before you see the answer - \end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise 4} -\begin{lstlisting} -def f(x): - def g(x): - return x + 1 - return g(x) - -f(1) -f(2) -\end{lstlisting} -\vspace*{0.1in} - \begin{itemize} - \item Run step-by-step on \url{pythontutor.com} - \item Predict the output before you see the answer - \end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise 5} -\begin{lstlisting} -def mul(x): - def g(y): - return y*x - return g - -twice = mul(2.0) -twice(20) -\end{lstlisting} -\vspace*{0.1in} - \begin{itemize} - \item Run step-by-step on \url{pythontutor.com} - \item Predict the output before you see the answer - \end{itemize} - -\end{frame} - - -\end{document} diff --git a/advanced_python/3_varargs_kwargs.tex b/advanced_python/3_varargs_kwargs.tex deleted file mode 100644 index 29f7e88..0000000 --- a/advanced_python/3_varargs_kwargs.tex +++ /dev/null @@ -1,181 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[*args, **kw]{Advanced Python} -\subtitle{Arbitrary arguments for functions} - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame} - \frametitle{Overview} - \begin{itemize} - \item Advanced unpacking - \item Variable arguments - \item Arbitrary keyword arguments - \item Unpacking arguments - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Advanced unpacking} - \vspace*{-0.1in} -\begin{lstlisting} -In []: a, b = 1, 2 # We know this! -\end{lstlisting} - \pause - \begin{itemize} - \item In Python 3.x we can also do - \end{itemize} -\begin{lstlisting} -In []: first, *rest = range(5) - -In []: first -Out[]: 0 - -In []: first, *middle, last = range(5) - -In []: middle -Out[]: [1, 2, 3] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Advanced unpacking ...} - \begin{itemize} - \item Also works for files - \end{itemize} -\begin{lstlisting} -In []: f = open('file.txt') - -In []: first, *ign, last = f.readlines() - -In []: f.close() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Arbitrary positional arguments} - \vspace*{-0.1in} - \begin{itemize} - \item Arbitrary positional arguments: \lstinline{*arg} - \end{itemize} - -\begin{lstlisting} -In []: def func(a, b, *args): - ...: print(a, b, args) -\end{lstlisting} -\pause -\begin{lstlisting} -In []: func(1, 2) -1 2 () - -In []: func(1, 2, 'a') -1 2 ('a',) - -In []: func(1, 2, 3, 'a') -1 2 (3, 'a') -\end{lstlisting} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Arbitrary positional arguments} - - Nothing special about \lstinline{args}: - -\begin{lstlisting} -In []: def func(a, b, *rest): - ...: print(a, b, rest) - -\end{lstlisting} -Also is perfectly valid -\end{frame} - -\begin{frame}[fragile] - \frametitle{Arbitrary keyword arguments} - \vspace*{-0.1in} - \begin{itemize} - \item Keyword arguments using \lstinline{**kw} - \end{itemize} -\begin{lstlisting} -In []: def func(a, b='b', **kw): - ...: print(a, b, kw) -\end{lstlisting} - \pause -\begin{lstlisting} -In []: func(1) -1 b {} - -In []: func(1, 2) -1 2 {} - -In []: func(1, b=2) -1 2 {} -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Arbitrary keyword arguments} -\begin{lstlisting} -In []: def func(a, b='b', **k): - ...: print(a, b, k) - -In []: func(1, c=3) -1 b {'c': 3} - -In []: func(1, c=3, d=4) -1 b {'c': 3, 'd': 4} -\end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Argument unpacking} -\begin{lstlisting} -In []: def func(a, b): - ...: print(a, b) - -In []: func(*[5, 10]) -5 10 - -In []: func(*(5, 10)) -5 10 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Argument unpacking ...} -\begin{lstlisting} -In []: def func(a=1, b=2): - ...: print(a, b) - -In []: func(**{'a':5, 'b':10}) -5 10 - -In []: func(**dict(a=5, b=10)) -5 10 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item Advanced unpacking - \item Arbitrary positional arguments with \lstinline{*args} - \item Arbitrary keyword arguments with \lstinline{**kw} - \item Argument unpacking - \end{itemize} -\end{frame} - - -\end{document} diff --git a/advanced_python/4_only_kwargs.tex b/advanced_python/4_only_kwargs.tex deleted file mode 100644 index 8d4caef..0000000 --- a/advanced_python/4_only_kwargs.tex +++ /dev/null @@ -1,95 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[only kwargs]{Advanced Python} -\subtitle{Keyword-only arguments} - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame}[fragile, plain] - \frametitle{Motivation} - \vspace*{-0.1in} - \begin{itemize} - \item One can mix positional and keyword arguments - \end{itemize} - \begin{lstlisting} -In []: def f(a, b=2): - ...: print(a, b) - -In []: f(a=2, b=3) -2 3 - -In []: f(b=2, a=3) -3 2 - -In []: f(10, 20) -1 2 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Motivation} - \begin{itemize} - \item Function changes: positional arguments change in order or number - \item Accidentally passing an extra argument - \item Can we have purely keyword arguments? - - \vspace*{0.5in} - \item Yes, in Python 3.x! - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Keyword-only arguments} - \begin{lstlisting} -In []: def f(a, *args, b=False): - ...: print(a, args, b) - -In []: f(1, 20) -1 (20,) False - -In []: f(1, b=20) -1 () 20 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Keyword-only arguments} - \noindent Without any extra arguments: -\vspace*{0.25in} - \begin{lstlisting} -In []: def f(a, *, b=False): - ...: print(a, b) - -In []: f(1, 20) -TypeError: f() takes 1 positional arg... -\end{lstlisting} -\pause - \begin{lstlisting} -In []: f(1, b=20) -1 20 - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Discussion} - \begin{itemize} - \item Solves the problem nicely - \item \typ{b}: can only be specified as keyword argument - - \item Cannot be called as a positional argument - \end{itemize} -\end{frame} - - -\end{document} diff --git a/advanced_python/5_closures.tex b/advanced_python/5_closures.tex deleted file mode 100644 index f3571ef..0000000 --- a/advanced_python/5_closures.tex +++ /dev/null @@ -1,105 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[Closures]{Advanced Python} -\subtitle{Closures} - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame} - \frametitle{Overview} - \begin{itemize} - \item Higher-order functions - \item Closures - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Recap of higher-order functions} - \begin{lstlisting} -In []: def sqr(x): - ...: return x*x - -In []: def sum(func, n): - ...: result = 0 - ...: for i in range(n): - ...: result += func(i) - ...: return result - -In []: sum(sqr, 5) -Out[]: 30 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Recap of higher-order functions} - \begin{lstlisting} -def f(): - def g(x): - return x+1 - return g - -In []: func = f() -In []: func(1) -In []: f()(1) # Also valid! - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Closures} - \begin{lstlisting} -def mul(x): - def g(y): - return y*x - return g - -In []: twice = mul(2.0) -In []: twice(20) -Out[]: 40.0 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Closures ...} - \begin{lstlisting} - -In []: thrice = mul(3.0) -In []: thrice(20) -Out[]: 60.0 - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Discussion} - \begin{itemize} - \item \typ{g} uses \typ{x} - \item \typ{x} is different in each case - \item So \typ{twice, thrice} ``curry'' the passed \typ{x} - \item This function is called a closure - \item Encloses its local environment - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Summary: Higher-order functions} - \begin{itemize} - \item Functions that manipulate functions - \item Passing a function as an argument - \item A function that returns another function - \item A closure - \end{itemize} -\end{frame} - -\end{document} diff --git a/advanced_python/6_practice_functions.tex b/advanced_python/6_practice_functions.tex deleted file mode 100644 index ce7c9d6..0000000 --- a/advanced_python/6_practice_functions.tex +++ /dev/null @@ -1,222 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[Practice advanced functions]{Advanced Python} -\subtitle{Practice advanced functions} - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: product of all arguments} - \begin{block}{} - Write a function called \lstinline{prod} that can be called with any - number of arguments (at least one) but computes the product of all the - given values as seen below. - \end{block} - -\begin{lstlisting} -In []: prod(2., 2.) -Out[]: 4.0 - -In []: prod(1, 2, 3) -Out[]: 6 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -def prod(*args): - res = 1.0 - for x in args: - res *= x - return res - -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Another solution} -\begin{lstlisting} -def prod(*args): - res = args[0] - for i in range(1, len(args)): - res *= args[i] - return res - -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Exercise: function applied to arguments} - \begin{block}{} - Write a function called \lstinline{apply} which takes a function followed - by an arbitrary number of arguments and returns a list with the function - applied to all the arguments as shown below. - \end{block} - -\begin{lstlisting} -In []: def twice(x): - ...: return x*2 - -In []: apply(twice, 1, 2) -Out[]: [2, 4] - -In []: apply(twice, 1, 2, 3) -Out[]: [2, 4, 6] - -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -def apply(f, *args): - result = [] - for arg in args: - result.append(f(arg)) - return result -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: number of kwargs} - \begin{block}{} - Write a function \lstinline{nkw} that takes an arbitrary number of - keyword arguments and returns the number of keyword arguments passed. - \end{block} - -\begin{lstlisting} -In []: nkw(x=1, y=2) -Out[]: 2 - -In []: nkw() -Out[]: 0 - -In []: nkw(x=1) -Out[]: 1 -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -def nkw(**kw): - return len(kw) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: name of kwargs} - \begin{block}{} - Write a function \lstinline{kwname} that takes an arbitrary number of - keyword arguments and returns a sorted list of the keyword arguments - passed. - \end{block} - -\begin{lstlisting} -In []: kwname(x=1, y=2) -Out[]: ['x', 'y'] - -In []: kwname() -Out[]: [] - -In []: kwname(z=1, a=2) -Out[]: ['a', 'z'] -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -def kwname(**kw): - return sorted(kw.keys()) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: power function} - \begin{block}{} - Write a function called \lstinline{power} that is given a single integer - and returns a function that takes a single number but returns its power. - For example: - \end{block} - -\begin{lstlisting} -In []: pow2 = power(2) -In []: pow2(2) -Out[]: 4 -In []: pow2(4) -Out[]: 16 - -In []: pow3 = power(3) -In []: pow3(2) -Out[]: 8 -\end{lstlisting} - Hint: this is a closure. -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -def power(n): - def g(x): - return x**n - return g - -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Exercise: debug function} - \begin{block}{} - Write a function called \lstinline{debug} that takes any function as a - single positional argument but returns a function that first prints out - the arguments passed to the function before calling it and returning its - value. For example: - \end{block} - -\begin{lstlisting} -In []: debug(max)(1, 2) -(1, 2) {} -Out[]: 2 - -In []: import math - -In []: debug(math.sin)(1.0) -(1.0,) {} -Out[]: 0.8414709848078965 - -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -def debug(f): - def g(*args, **kw): - print(args, kw) - return f(*args, **kw) - return g -\end{lstlisting} -\end{frame} - - -\end{document} diff --git a/advanced_python/7_oop_basics.tex b/advanced_python/7_oop_basics.tex deleted file mode 100644 index d6f4e24..0000000 --- a/advanced_python/7_oop_basics.tex +++ /dev/null @@ -1,316 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[Introduction to OOP]{Advanced Python} -\subtitle{Introduction to Object Oriented Programming } - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame} - \frametitle{Background and caveats} - \begin{itemize} - \item You don't need OOP for everything! - \item Helps with larger programs - \item Appreciate it, when you write more code - \item Very useful to organize/modularize your code - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{What are the benefits?} - \begin{itemize} - \item Create new data types - \item Create objects to simulate a real problem - \item Makes problem solving more natural and elegant - \item Can be easier to understand - \item Allows for code-reuse - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Example: Managing Talks} - \begin{itemize} - \item Want to manage list of talks at a conference - \end{itemize} - \begin{lstlisting} -talk = {'Speaker': 'Guido van Rossum', - 'Title': 'The History of Python' - 'Tags': 'python,history,C,advanced'} - -def get_first_name(talk): - return talk['Speaker'].split()[0] - -def get_tags(talk): - return talk['Tags'].split(',') - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Issues} - \begin{itemize} - \item Not convenient to handle large number of talks - \item Data separate from functions to manipulate talk - \item Must pass \lstinline{talk} to each function - \item No clear organization - \item What if we had different kinds of talks? - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Creating a \typ{class}} - \begin{lstlisting} -class Talk: - """A class for the Talks.""" - def __init__(self, speaker, title, tags): - self.speaker = speaker - self.title = title - self.tags = tags - \end{lstlisting} - \begin{itemize} - \item \lstinline{class} is a keyword - \item \lstinline{Talk} is the name of the class - \item Notice the class doc-string - \item Notice the indentation - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{methods and \lstinline{self}} - \begin{lstlisting} -class Talk: - # ... - def get_speaker_firstname(self): - return self.speaker.split()[0] - - def get_tags(self): - return self.tags.split(',') - \end{lstlisting} - \begin{itemize} - \item \lstinline{self} is a reference to the object itself - \item The name \lstinline{self} is a convention - \item Instance variables: \lstinline{self.name} - \end{itemize} -\end{frame} - -\begin{frame}[fragile, plain] - \frametitle{Exercise: type this out} - \vspace*{-0.1in} - \begin{lstlisting} -class Talk: - """A class for the Talks.""" - def __init__(self, speaker, title, tags): - self.speaker = speaker - self.title = title - self.tags = tags - - def get_speaker_firstname(self): - return self.speaker.split()[0] - - def get_tags(self): - return self.tags.split(',') - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Instantiating a class to create objects} - \begin{itemize} - \item Creating objects or instances of a class is simple - \item Call class, with arguments required by \lstinline{__init__} - \end{itemize} - \begin{lstlisting} -In []: bdfl = Talk('Guido van Rossum', - ...: 'The History of Python', - ...: 'python,history,C,advanced') - \end{lstlisting} - \begin{itemize} - \item We can now call the methods of the Class - \end{itemize} - \begin{lstlisting} -In []: bdfl.get_tags() -In []: bdfl.get_speaker_firstname() - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\lstinline{__init__} method} - \begin{itemize} - \item A special method - \item Called every time an instance of the class is created - \end{itemize} - \begin{lstlisting} -In []: print(bdfl.speaker) -In []: print(bdfl.tags) -In []: print(bdfl.title) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Creating more instances} - \begin{lstlisting} -In []: talk = Talk('Arun K', - ...: 'Python in biosciences', 'python,bio') -In []: talk.get_tags() -In []: talk.tags - -In []: type(talk) -Out[]: __main__.Talk -In []: type(bdfl) -\end{lstlisting} -\begin{itemize} -\item Note that \lstinline{talk} and \lstinline{bdfl} are different objects -\item Different values but same type -\item \lstinline{Talk} \alert{encapsulates} the data and behavior of a talk -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Changing/adding attributes} -\begin{lstlisting} -In []: talk.speaker = 'Arun K P' - -In []: talk.tags = 'python,bioscience' -\end{lstlisting} -\pause -\begin{lstlisting} -# Adding attributes - -In []: talk.x = 1 - -In []: talk.y = 'hello' -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item Introduction to Object Oriented Programming - \item A simple example - \item Defining a \lstinline{class} - \item Methods and attributes: encapsulation - \item Changing/adding attributes - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise: simplest class} - \begin{block}{} - Create the simplest possible class, called \lstinline{Simple}, which has - no attributes or methods. Try this out on your own IPython interpreters. - You should be able to instantiate it as follows: - \end{block} -\begin{lstlisting} -In []: s = Simple() -\end{lstlisting} - \pause - \begin{block}{Hint} - Remember the \lstinline{pass} statement? - \end{block} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Simple: - pass -\end{lstlisting} - \vspace*{0.5in} - - That is all! -\end{frame} - -\begin{frame}[fragile,plain, fragile] - \frametitle{Exercise: \lstinline{Person} class 1} - \begin{block}{} - Create a simple \lstinline{Person} class with two attributes: a - \lstinline{name} (a string) and an \lstinline{age} (a float). To be used - as follows: - \end{block} -\begin{lstlisting} -In []: p = Person('Arun', 22.0) -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Person: - def __init__(self, name, age): - self.name = name - self.age = age -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: \lstinline{Person} class 2} - \begin{block}{} - Create a simple \lstinline{Person} class with two attributes a - \lstinline{name} and an \lstinline{age}. However, let the name default to - the string \lstinline{'name'} and the age default to 0.0. - \end{block} -\begin{lstlisting} -In []: p = Person() -In []: print(p.name, p.age) -name 0.0 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Person: - def __init__(self, name='name', age=0.0): - self.name = name - self.age = age -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain, fragile] - \frametitle{Exercise: simple method} - \begin{block}{} - Create a simple \lstinline{Person} class with two attributes as before. - Add a method called \lstinline{birthday} which takes no arguments and - which prints \lstinline{'HBD '} and also increases the age by 1. - Note that \lstinline{} is the name of the instance. - \end{block} - -\begin{lstlisting} -In []: p = Person(name='Ram') -In []: p.birthday() -HBD Ram -In []: p.age -Out[]: 1.0 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Person: - def __init__(self, name='name', age=0.0): - self.name = name - self.age = age - - def birthday(self): - print('HBD', self.name) - self.age += 1.0 -\end{lstlisting} -\end{frame} - - - -\end{document} diff --git a/advanced_python/8_oop_inheritance.tex b/advanced_python/8_oop_inheritance.tex deleted file mode 100644 index 657dfad..0000000 --- a/advanced_python/8_oop_inheritance.tex +++ /dev/null @@ -1,531 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[OOP Inheritance]{Advanced Python} -\subtitle{Object Oriented Programming: Inheritance} - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame} - \frametitle{Recap} - \begin{itemize} - \item Created a new \lstinline{Talk} class - \item Puts together data and methods - \item Can make instances of the class - \item Each instance has its own data - \item Objects encapsulate data and behavior - \end{itemize} -\end{frame} - -\begin{frame}[fragile, plain] - \frametitle{Recap: the Talk class} - \vspace*{-0.1in} - \begin{lstlisting} -class Talk: - """A class for the Talks.""" - def __init__(self, speaker, title, tags): - self.speaker = speaker - self.title = title - self.tags = tags - - def get_speaker_firstname(self): - return self.speaker.split()[0] - - def get_tags(self): - return self.tags.split(',') - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Instantiating a class to create objects} - \begin{lstlisting} -In []: bdfl = Talk('Guido van Rossum', - ...: 'The History of Python', - ...: 'python,history,C,advanced') -In []: bdfl.get_tags() -In []: bdfl.get_speaker_firstname() -In []: bdfl.tags - -In []: type(bdfl) - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Classes: the big picture} - \begin{itemize} - \item Lets you create new data types - \item Class is a template for an object belonging to that class - \item Instantiating a class creates an instance (an object) - \item An instance encapsulates the state (data) and behavior - (methods) - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Objects and Methods} - \begin{itemize} - \item Objects group data with functions - \item Everything in Python is an object - \item Strings, lists, functions and even modules - \end{itemize} - \begin{lstlisting} - s = "Hello World" - s.lower() - - l = [1, 2, 3, 4, 5] - l.append(6) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes} - \begin{lstlisting} -In []: s = "Hello World" -In []: type(s) - \end{lstlisting} - \begin{itemize} - \item A new string, comes along with methods - \item A template or a blue-print, where these definitions lie - \item This blue print for building objects is called a - \lstinline{class} - \item \lstinline{s} is an object of the \lstinline{str} class - \item An object is an ``instance'' of a class - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Classes: inheritance} - \begin{itemize} - \item Allows you to define an inheritance hierarchy - \begin{itemize} - \item ``A Honda car \alert{is a} car.'' - \item ``A car \alert{is an} automobile.'' - \item ``A Python \alert{is a} reptile.'' - \end{itemize} - \item All data/behavior of a car should be there in a ``Honda'' car - \item All data/behavior associated with a reptile ought to inhere in a snake - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Inheritance} - \vspace*{-0.1in} - \begin{itemize} - \item Suppose, we wish to write a \lstinline{Tutorial} class - \item It's almost same as \lstinline{Talk} except for minor differences - \item We can ``inherit'' from \lstinline{Talk} - \end{itemize} - \pause - \begin{lstlisting} -class Tutorial(Talk): - """A class for the tutorials.""" - def __init__(self, speaker, title, tags, - needs_computer=True): - super().__init__(speaker, title, tags) - self.needs_computer = needs_computer - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Inheritance} - \vspace*{-0.1in} - \begin{itemize} - \item Modified \lstinline{__init__} method - \item Inherits: \lstinline{get_tags} and - \lstinline{get_speaker_firstname} - \end{itemize} - \begin{lstlisting} -tut = Tutorial('Travis Oliphant', - 'Numpy Basics', - 'numpy,python,beginner') -tut.get_speaker_firstname() -tut.needs_computer - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Some points} - \begin{itemize} - \item \lstinline{Tutorial} is a subclass (or child) of \lstinline{Talk} - \item \lstinline{Tutorial} is derived from (inherits from) \lstinline{Talk} - \item \lstinline{Talk} is the base class (or parent class) - \item Only the \lstinline{__init__} has been changed - \item This is called overriding - \item \lstinline{super} ensures that the parent class is called - \item Calling the parent is not automatic - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise: try this} -\begin{lstlisting} -class Tutorial(Talk): - def __init__(self, speaker, title, tags, - needs_computer=True): - self.needs_computer = needs_computer - -In []: t = Tutorial('G v R', 'Python', 'py,tut') - -In []: t.needs_computer - -In []: t.speaker - -In []: t.get_speaker_firstname() - -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Inheritance} - \begin{itemize} - \item A \lstinline{Tutorial} is a \lstinline{Talk} - \item A \lstinline{Talk} is not a \lstinline{Tutorial} - \item The sentence above should make sense! - \item A \lstinline{Cat} is an \lstinline{Animal} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Incorrect inheritance} - \begin{itemize} - \item A \lstinline{Talk} is a \lstinline{Speaker} or - \item A \lstinline{Speaker} is a \lstinline{Room} - \item Something is wrong in your OO design! - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item Inheritance - \item The importance of making sense - \item The \lstinline{super} function - \end{itemize} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Exercises - -\begin{frame}[fragile] - \frametitle{Exercise: \lstinline{Animal} class} - \begin{block}{} - Create an \lstinline{Animal} class that has a name attribute (str) and a - single method called \lstinline{greet} which takes no arguments but returns - a string about how the animal makes a greeting. By default let - \lstinline{greet} return \lstinline{' says greet'}. - \end{block} -\begin{lstlisting} -In []: a = Animal('human') -In []: a.greet() -Out[]: 'human says greet' -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Animal: - def __init__(self, name): - self.name = name - def greet(self): - return self.name + ' says greet' -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Solution} - \begin{itemize} - \item Note that this is the same as - \end{itemize} -\begin{lstlisting} -class Animal(object): - # ... -\end{lstlisting} - \begin{itemize} - \item Otherwise \lstinline{object} is implicitly the base class - \end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise: \lstinline{Cat} class} - \begin{block}{} - Create a \lstinline{Cat} class which derives from the \lstinline{Animal} - class \alert{override} \lstinline{greet} return - \lstinline{' says meow'}. - \end{block} -\begin{lstlisting} -In []: a = Cat('Felix') -In []: a.greet() -Out[]: 'Felix says meow' -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Animal: - def __init__(self, name): - self.name = name - def greet(self): - return self.name + ' says greet' - -class Cat(Animal): - def greet(self): - return self.name + ' says meow' -\end{lstlisting} - \begin{itemize} - \item Note, no need to override \lstinline{__init__} - \end{itemize} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Observation: order matters} -\begin{lstlisting} -class Cat(Animal): - def greet(self): - return self.name + ' says meow' - -class Animal: - def __init__(self, name): - self.name = name - def greet(self): - return self.name + ' says greet' - -\end{lstlisting} - \begin{itemize} - \item Will the above code work? Explore this and see what error you get. - \end{itemize} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Exercise: \lstinline{Mammal} class} - \begin{block}{} - Create a \lstinline{Mammal} class that derives from \lstinline{Animal} - that takes an additional argument specifying the number of legs (an - integer) and stores it in the attribute \lstinline{legs}. - \end{block} - -\begin{lstlisting} -In []: m = Mammal('dog', 4) -In []: m.legs -Out[]: 4 -In []: m.greet() -Out[]: 'dog says greet' -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Mammal(Animal): - def __init__(self, name, legs): - super().__init__(name) - self.legs = legs -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution alternative} -\begin{lstlisting} -class Mammal(Animal): - def __init__(self, name, legs): - self.name = name - self.legs = legs -\end{lstlisting} - \begin{itemize} - \item Will also work but a \alert{bad} idea - \item What if \lstinline{Animal.__init__} changes? - \end{itemize} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{More on \typ{super}} -We can also do: -\begin{lstlisting} -class Mammal(Animal): - def __init__(self, name, legs): - super(Mammal, self).__init__(name) - -In []: super? - -In []: m = Mammal('dog', 4) -In []: super(Mammal, m) - -In []: super(Mammal, m).greet() - -In []: super(Animal, m).greet() # ?? -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Exercise: \lstinline{Human} class} - \begin{block}{} - Create a \lstinline{Human} class that derives from \lstinline{Mammal} - modify its \lstinline{greet} method to return - \lstinline{' says hello'}. Also change the default number of legs - to 2. - \end{block} - -\begin{lstlisting} -In []: h = Human('Ram') -In []: h.legs -Out[]: 2 -In []: h.greet() -Out[]: 'Ram says hello' -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Human(Mammal): - def __init__(self, name, legs=2): - super().__init__(name, legs) - def greet(self): - return self.name + ' says hello' -\end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Complete Solution} - \vspace*{-0.1in} - \small -\begin{lstlisting} -class Animal: - def __init__(self, name): - self.name = name - def greet(self): - return self.name + ' says greet' - -class Mammal(Animal): - def __init__(self, name, legs): - super().__init__(name) - self.legs = legs - -class Human(Mammal): - def __init__(self, name, legs=2): - super().__init__(name, legs) - def greet(self): - return self.name + ' says hello' -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Observations} - \begin{itemize} - \item \py{Human} is a \py{Mammal} - \item \py{Human} is an \py{Animal} - \end{itemize} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Exercise: Methods in subclass} - \begin{block}{} - Add a method to \py{Human} called \py{speak} which prints - \py{'My name is '}. - \end{block} - -\begin{lstlisting} -In []: h = Human('Ram') -In []: h.speak() -My name is Ram -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Human(Mammal): - def __init__(self, name, legs=2): - super().__init__(name, legs) - def greet(self): - return self.name + ' says hello' - def speak(self): - print('My name is', self.name) -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Observations} - \begin{itemize} - \item \py{Human} is a \py{Mammal} - \item \py{Human} is an \py{Animal} - \item \py{Human} can speak but \py{Mammal, Animal} cannot - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise: class in a module} - - \begin{block}{} - Put the \py{Animal, Mammal, Human} classes inside a Python file, called - \texttt{oop.py} somewhere convenient in your computer. Add the following - code at the bottom. - \end{block} -\begin{lstlisting} -print(__name__) -h = Human('Sam') -print(h.greet()) -print(h.legs) -print(type(h)) -\end{lstlisting} - - \begin{itemize} - \item Execute this module using \texttt{python oop.py} - \item Import the \py{Human} class from IPython - \end{itemize} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: overriding a \typ{list} method} - \begin{block}{} - Create a subclass of the standard Python \py{list} called \py{MyList} and - override just the \py{append} method to print the item appended as - \py{'appending '} and then call the parent append so as to - internally append the item. The usage should be as follows: - \end{block} - -\begin{lstlisting} -In []: l = MyList() -In []: l.append(1) -appending 1 -In []: l -Out[]: [1] -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class MyList(list): - def append(self, item): - print('appending', item) - super().append(item) -\end{lstlisting} -\end{frame} - - - -\end{document} diff --git a/advanced_python/9_oop_containership.tex b/advanced_python/9_oop_containership.tex deleted file mode 100644 index 6434819..0000000 --- a/advanced_python/9_oop_containership.tex +++ /dev/null @@ -1,207 +0,0 @@ -\documentclass[14pt,compress,aspectratio=169]{beamer} - -\input{macros.tex} - -\title[OOP containership]{Advanced Python} -\subtitle{Object Oriented Programming: containership } - -\author[FOSSEE] {The FOSSEE Group} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {Mumbai, India} - -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\begin{frame} - \frametitle{Recap} - \begin{itemize} - \item Created \lstinline{Talk} and \lstinline{Tutorial} classes - \item Know how to create objects: instantiation of a class - \vspace*{0.5in} - - \item Let us create a conference! - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Conference class} - \vspace*{-0.1in} -\begin{lstlisting} -class Conference: - def __init__(self, talks=None): - if talks is None: - talks = [] - self.talks = talks - - def add_talk(self, talk): - self.talks.append(talk) - - def schedule(self): - for talk in self.talks: - print(talk.speaker, talk.title) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Using this} -\begin{lstlisting} -In []: c = Conference() - -In []: t = Talk('Guido', 'Python4', 'py,core') - -In []: c.add_talk(t) - -In []: c.schedule() - -\end{lstlisting} - \begin{itemize} - \item Easy to read - \item Nicely split up - \item Reflects the real world - - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{But why not this?} -\begin{lstlisting} -class Conference: - def __init__(self, talks=[]): - self.talks = talks -\end{lstlisting} - \begin{itemize} - \item Easier - \item Less code - \item Let's try it! - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Gotcha!} -\begin{lstlisting} -In []: c1 = Conference() -In []: c1.add_talk(1) -In []: c1.talks - -In []: c2 = Conference() -In []: c2.talks - -\end{lstlisting} - - \begin{itemize} - \item What is going on? - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Beware of mutable default arguments!} - \begin{itemize} - \item Default arguments are evaluated once - \item When the method/function is defined - \item So, if the object is mutable we have a problem - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Which is why we have this} -\begin{lstlisting} -class Conference: - def __init__(self, talks=None): - if talks is None: - talks = [] - self.talks = talks -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Containership} - \begin{itemize} - \item \lstinline{Conference} class manages all the talks - \item It contains the talks and tutorials - \item Allows us to build complexity by \alert{composition} - \item Hierarchical organization - \item Allows us to mirror the real objects in code - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Some more examples} - \begin{itemize} - \item OOP for a \lstinline{Company} - \item OOP for a \lstinline{Bank} - \item OOP for a \lstinline{School} or \lstinline{College} - \item OOP for a cell phone, computer, ... - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Design guidelines} - \begin{itemize} - \item Important to make sense - \item Should be easy to explain the relationships and responsibilities of - each class - \item Inheritance should ``read'' correctly and make sense - \item No object should be too responsible - \item Functionality should be suitably delegated - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item Creating a more complex class - \item Containing other objects - \item Issue with mutable default arguments - \item Important design guidelines - \end{itemize} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: Create a Zoo} - \begin{block}{} - Create a \py{Zoo} class which allows someone to add any number of animals. - This means it should work for \py{Animal, Mammal, Human} objects. It - should have a single \py{greet} method which calls the greet method of all - of the animals it has and prints that: - \end{block} - -\begin{lstlisting} -In []: b = Animal('crow') -In []: m = Mammal('dog', legs=4) -In []: h = Human('Abhinav') -In []: z = Zoo(b, m, h) -In []: z.greet() -crow says greet -dog says greet -Abhinav says hello -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain, fragile] - \frametitle{Solution} -\begin{lstlisting} -class Zoo: - def __init__(self, *animals): - self.animals = list(animals) - - def greet(self): - for animal in self.animals: - print(animal.greet()) -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Observations} - \begin{itemize} - \item Notice the abstraction of \py{Animal} - \item The \py{Zoo} will work with any object that has the \py{greet} method - \item That is, any \py{Animal} - \end{itemize} -\end{frame} - -\end{document} diff --git a/advanced_python/Makefile b/advanced_python/Makefile index b0b761a..b16d42b 100644 --- a/advanced_python/Makefile +++ b/advanced_python/Makefile @@ -4,15 +4,15 @@ pdflatex $*.tex pdflatex $*.tex -SLIDES= 1_intro.pdf \ - 2_names_objects.pdf \ - 3_varargs_kwargs.pdf \ - 4_only_kwargs.pdf \ - 5_closures.pdf \ - 6_practice_functions.pdf \ - 7_oop_basics.pdf \ - 8_oop_inheritance.pdf \ - 9_oop_containership.pdf \ +SLIDES= 01_intro.pdf \ + 02_names_objects.pdf \ + 03_varargs_kwargs.pdf \ + 04_only_kwargs.pdf \ + 05_closures.pdf \ + 06_practice_functions.pdf \ + 07_oop_basics.pdf \ + 08_oop_inheritance.pdf \ + 09_oop_containership.pdf \ 10_oop_classattr.pdf \ 11_oop_misc.pdf \ 12_oop_simple_special_methods.pdf \ -- cgit