Verified Commit 21fc92a3 authored by Bisca's avatar Bisca
Browse files

Import from 2017 talk

parents
## vim swap files
*.swp
## SCSS
*.scss
Copyright (C) 2017 Hakim El Hattab, http://hakim.se, and reveal.js contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
# POuL reveal.js template
This is a base template that will allow you to make state-of-art presentations
using advanced technologies such as Markdown, reveal.js (thus the
industry-standard language JavaScript), still complying with the mandatory
design guidelines.
## How do I use this thing?
### Where do I write my stuff?
[Download][download] this repo and put your content inside the 'content.md'
file placed in the root of this directory. What were you expecting?
### How do I write my stuff?
Using a text editor and typing Markdown syntax on your keyboard.
[Here][markdown-guide] you can find a comprehensive guide to the syntax.
Remember to use three dashes (`---`) to create a new slide horizontally and
four dashes (`----`) to create a new one vertically.
### How do I see my stuff?
Make sure you have Python 3 installed. Nothing more is required.
Make the deploy.py script executable with
chmod +x deploy.py
Then just run
./deploy.py --show
A new tab will open in your default browser showing the presentation.
You can spacify your browser using the `BROWSER` environment variable.
BROWSER=surf ./deploy.py --show
You can see what kind of trickery this script is able to do running it with the
`-h` or `--help` flag.
#### Why?
This is required since modern browsers won't allow you to include a local file
(the Markdown document) from JavaScript.
The Python script will run a small HTTP server and fix this issue.
## How do I make a PDF out of the slides?
Append `?print-pdf` at the end of the URL.
For instance if you're running the `deploy.py` script locally the URL will be
something like `http://127.0.0.1:8080/?print-pdf`.
Then just use the print function of your browser to make a PDF of the page.
[download]: https://gitlab.poul.org/corsi/revealjs-poul/repository/archive.zip?ref=master
[markdown-guide]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet
# Corsi Python 2017
![POuL logo](lib/img/logo-text-white.svg)
- Giacomo Vercesi
`<1vercesig_chiocciola_gmail.com>`
----
## Programmazione ad Oggetti
Potete ottenere questa presentazione recandovi all'indirizzo:
[slides.poul.org/2017/python](https://slides.poul.org/2017/python)
---
### Perché la programmazione ad oggetti?
* perché in Python tutto è un oggetto
* permette di moddellare il programma come un insieme di entità comunicanti
tra di loro
* racchiudere insieme le variabili e il codice che le modifica
----
## Cos'è una classe
* un contenitore di variabili e funzioni
* le funzioni modificano queste variabili
* le variabili si chiamano **attributi**
* le funzioni si chiamano **metodi**
----
## Cos'è un'oggetto
È quando una classe prende vita.
```python
class Classe:
pass
oggetto = Classe()
```
Si dice che `oggetto` è una **istanza** di `Classe`.
----
### Scavare dentro gli oggetti
Il comando `dir()` restituisce il contenuto di un oggetto, asstributi e metodi.
```python
>>> dir("Ciao")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
...
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
```
---
* La variabile `self`
* Il primo parametro di ogni metodo è sempre l'istanza su cui si sta operando
* Convenzionalmente si chiama `self`
* La funzione `__init__()`:
* Inizializza l'oggetto
```python
class Contatore():
def __init__(self):
self.numero = 0
def aumenta(self, incremento=1):
self.numero += incremento
```
----
### Perché tutti questi *underscore*?
È una convenzione.
* **`variabile`**: variabile generica
* **`_variabile`**: variabile privata. È consigliato non modificarla
* **`__variabile`**: variabile interna. Modificarla potrebbe creare
problemi
* **`__variabile`**: variabile interna del linguaggio. Da non modificare
* **`variabile_`**: da usare se esiste una variabile built-in con lo stesso
nome
---
## Duck Typing
> «If it looks like a duck, walks like a duck and quacks like a duck
> then it just may be a duck»
> ***---Walter Reuther***
> «Se un oggetto ha un metodo `read()`, `write()` e `seek()`, `flush()`, ...
allora è un file»
> ***---Python***
----
### `__getitem__()`
* È possibile creare una classe che si comporta come una lista.
* Possiamo accedere ai suoi elementi usando la sintassi `oggetto[indice]`
```python
class Tabellina8():
def __getitem__(self, i):
return 8*i
```
```
>>> t = Tabellina8()
>>> t[3]
24
```
----
### Context manager
* Sono definiti dal costrutto `with` seguito da un blocco
* Permettono di eseguire del codice prima e dopo il blocco
```python
with open("test.txt", 'w') as f:
f.write("Ciao")
print("Finito di scrivere su file")
```
* `open()` all'inizio del blocco apre il file.
* `open()` ritorna una instanza e assume all'interno del blocco il nome `f`
* `f` continua a vivere dopo il blocco, ma può non avere significato (`f`
fuori dal blocco non è più utilizzabile per leggere e scrivere sul file)
----
### Creare classi con context manager
Basta definire i metodi `__enter__()` e `__exit__()` all'interno della classe.
```python
class Contesto:
def __enter__(self):
print('apro il contesto')
def __exit__(self, type, value, traceback):
print('chiudo il contesto')
with Contesto()
print('azione')
```
----
## Alcuni esempi aggiuntivi
* `'*' --> __mul__(a, b)`
* `'+' --> __add__(a, b)`
* `print --> __str__()`
Per una lista più esaustiva
(https://docs.python.org/3/reference/datamodel.html)
---
## Ereditarietà
* Permette di definire sottoinsiemi (sottoclassi).
* La classe figlio ottiene attributi e metodi dalla classe padre.
----
```python
class Contatore():
def __init__(self):
self.numero = 0
def aumenta(self, incremento=1):
self.numero += incremento
class Contatore2(Contatore):
def aumenta(self, incremento=1):
self.ultimo_accesso = int(time.time())
super().aumenta(incremento)
def ultimo_incremento(self):
tempo_passato = int(time.time()) - self.ultimo_accesso
print("Ultimo incremento {} secondi fa"
.format(tempo_passato))
```
----
### `super()`
La funzione `super()` ritorna l'oggetto corrente castato alla classe padre.
---
## Eccezioni
----
### Cosa sono?
Le eccezioni sono un meccanismo per comunicare che c'è una situazione anomala
all'interno del programma
----
#### Come gestiamo le eccezioni?
```python
a = int(input("Inserisci numeratore: "))
b = int(input("Inserisci denominatore: "))
try:
c = a/b
print("{}/{} è {}".format(a,b,c))
except ZeroDivisionError:
print("Denominatore 0, impossibile eseguire divisione)
```
----
### Sollevare un'eccezione
Usiamo la funzione 'raise()'.
```python
raise ZeroDivisionError("Messaggio di errore")
```
----
### Definire le eccezioni
```python
class IncrementoZeroError(Exception):
pass
```
---
## Getter e Setter
----
#### Once upon a time in java...
```java
private int colore;
int getColore(){
return this.colore;
}
int setColore(int colore){
this.colore = colore;
}
```
----
### Back to python land...
```python
class Colore():
def __init__(self):
self.intero = 0xffffff
@property
def colore(self):
return '#' + hex(self.intero)[2:]
@colore.setter
def colore(self, colore):
self.intero = int(colore[1:], 16)
```
```
>>> c = Colore()
>>> c.colore
#ffffff
>>> c.colore = '#aabbcc'
>>> c.colore
#aabbcc
```
---
# Thank you!
![POuL logo](lib/img/logo-text-white.svg)
![Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](lib/img/creativecommons-by-nc-sa.svg)
# Example
---
- Lorem ipsum
- Dolor sit amet
- Consectetur adipiscing elit
----
- Integer nec
- neque id ante
- Aliquam fermentum
---
- Use three (3) dashes (`---`) to move horizontally
- Use four (4) dashes (`----`) to move vertically
----
This is a long dash -- made of two little dashes (`--`).
This dash is even longer --- and it is made of three little dashes (`---`).
"Quoting" is fun and easy. `"`Plain quoting`"` is ugly.
----
```python
x = 1 + 2
if x > 2:
pass
try:
with open('/dev/null') as f:
pass
except IOError:
raise Exception('Error!')
finally:
sys.exit()
```
/* Default Print Stylesheet Template
by Rob Glazebrook of CSSnewbie.com
Last Updated: June 4, 2008
Feel free (nay, compelled) to edit, append, and
manipulate this file as you see fit. */
@media print {
/* SECTION 1: Set default width, margin, float, and
background. This prevents elements from extending
beyond the edge of the printed page, and prevents
unnecessary background images from printing */
html {
background: #fff;
width: auto;
height: auto;
overflow: visible;
}
body {
background: #fff;
font-size: 20pt;
width: auto;
height: auto;
border: 0;
margin: 0 5%;
padding: 0;
overflow: visible;
float: none !important;
}
/* SECTION 2: Remove any elements not needed in print.
This would include navigation, ads, sidebars, etc. */
.nestedarrow,
.controls,
.fork-reveal,
.share-reveal,
.state-background,
.reveal .progress,
.reveal .backgrounds,
.reveal .slide-number {
display: none !important;
}
/* SECTION 3: Set body font face, size, and color.
Consider using a serif font for readability. */
body, p, td, li, div {
font-size: 20pt!important;
font-family: Georgia, "Times New Roman", Times, serif !important;
color: #000;
}
/* SECTION 4: Set heading font face, sizes, and color.
Differentiate your headings from your body text.
Perhaps use a large sans-serif for distinction. */
h1,h2,h3,h4,h5,h6 {
color: #000!important;
height: auto;
line-height: normal;
font-family: Georgia, "Times New Roman", Times, serif !important;
text-shadow: 0 0 0 #000 !important;
text-align: left;
letter-spacing: normal;
}
/* Need to reduce the size of the fonts for printing */
h1 { font-size: 28pt !important; }
h2 { font-size: 24pt !important; }
h3 { font-size: 22pt !important; }
h4 { font-size: 22pt !important; font-variant: small-caps; }
h5 { font-size: 21pt !important; }
h6 { font-size: 20pt !important; font-style: italic; }
/* SECTION 5: Make hyperlinks more usable.
Ensure links are underlined, and consider appending
the URL to the end of the link for usability. */
a:link,
a:visited {
color: #000 !important;
font-weight: bold;
text-decoration: underline;
}
/*
.reveal a:link:after,
.reveal a:visited:after {
content: " (" attr(href) ") ";
color: #222 !important;
font-size: 90%;
}
*/
/* SECTION 6: more reveal.js specific additions by @skypanther */
ul, ol, div, p {
visibility: visible;
position: static;
width: auto;
height: auto;
display: block;
overflow: visible;
margin: 0;
text-align: left !important;
}
.reveal pre,
.reveal table {
margin-left: 0;
margin-right: 0;
}
.reveal pre code {
padding: 20px;
border: 1px solid #ddd;
}
.reveal blockquote {
margin: 20px 0;
}
.reveal .slides {
position: static !important;
width: auto !important;
height: auto !important;
left: 0 !important;
top: 0 !important;
margin-left: 0 !important;
margin-top: 0 !important;
padding: 0 !important;
zoom: 1 !important;
overflow: visible !important;
display: block !important;
text-align: left !important;
-webkit-perspective: none;
-moz-perspective: none;
-ms-perspective: none;
perspective: none;
-webkit-perspective-origin: 50% 50%;
-moz-perspective-origin: 50% 50%;
-ms-perspective-origin: 50% 50%;
perspective-origin: 50% 50%;
}
.reveal .slides section {
visibility: visible !important;
position: static !important;
width: auto !important;
height: auto !important;
display: block !important;
overflow: visible !important;
left: 0 !important;
top: 0 !important;
margin-left: 0 !important;
margin-top: 0 !important;
padding: 60px 20px !important;
z-index: auto !important;
opacity: 1 !important;
page-break-after: always !important;
-webkit-transform-style: flat !important;
-moz-transform-style: flat !important;
-ms-transform-style: flat !important;
transform-style: flat !important;
-webkit-transform: none !important;
-moz-transform: none !important;
-ms-transform: none !important;
transform: none !important;
-webkit-transition: none !important;
-moz-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}
.reveal .slides section.stack {
padding: 0 !important;
}
.reveal section:last-of-type {
page-break-after: avoid !important;
}
.reveal section .fragment {
opacity: 1 !important;
visibility: visible !important;
-webkit-transform: none !important;
-moz-transform: none !important;
-ms-transform: none !important;
transform: none !important;
}
.reveal section img {
display: block;
margin: 15px 0px;
background: rgba(255,255,255,1);
border: 1px solid #666;
box-shadow: none;
}