Le stringhe str
sono piu complesse di int
e float
.
E' possibile pensarle codificate in memoria come vettori
(sequenze di elementi uguali).
nome = 'andrea sterbini'
carattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|
len(nome)
random access
) a ciascun caratterenome[4]
nome[0]
è il primo elementocarattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|
nome[0]
'a'
nome[100] #attenzione il mio nome e cognome non arriva a 100 caratteri
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_9389/2238065423.py in <cell line: 1>() ----> 1 nome[100] #attenzione il mio nome e cognome non arriva a 100 caratteri IndexError: string index out of range
len(nome) #infatti i caratteri sono 15
15
# ok accediamo all quindicesimo
nome[15]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_9389/3779975648.py in <cell line: 2>() 1 # ok accediamo all quindicesimo ----> 2 nome[15] IndexError: string index out of range
carattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|
start = nome[0] # accedo al primo elemento, lo metto dentro start
end = nome[len(nome)-1] # calcolo la lunghezza della stringa.
# ultimo elemento è in posizione luneghezza-1. Ci accedo
# lo metto dentro end
print(start) #stampa la prima lettera
print(end) #stampa l'ultima lettera
a i
# Posso invece contare dalla fine
ultimo = nome[-1]
penultimo = nome[-2]
print(ultimo)
print(penultimo)
i n
# possiamo anche "affettare" la stringa
# per estrarre il mio nome (slicing)
nome[0:6] # da notare MOLTO IMPORTANTE
# 0 e' compreso, 6 escluso
'andrea'
car.| a | n | d | r | e | a | ----|---|---|---|---|---|---| idx | 0 | 1 | 2 | 3 | 4 | 5 |
Assumiamo di volere estrarre drea
da andrea sterbini
.
carattere | a | n | d | r | e | a | | s | t | e | r | b | i | n | i | -- | -- | --| --| --| --| --| --| --| --| --| --| --| --| --| --| indice | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|
:
da 2 a 6 ossia [2:6]
(prendi la fetta che va dall'indice 2 al 6 escluso)gli indici di slicing
in python sono sempre $[\text{ start},\text{end })$start
incluso, end
ESCLUSOsub_name = nome[2:6]
print(sub_name)
drea
E se non sappiamo dove inizia drea
, che facciamo?
drea
drea
è lungo 4 caratteri, ma possiamo usare il metodo len()
per calcolarsi la lunghezza della stringa, cosi funzionerà con tutte le stringhe, non solo con drea
.drea
dentro nome
?Se ci fate caso ci stiamo piano piano approcciando al problem solving
help(str) # conviene leggersi le funzionalita' del tipo str
Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.__str__() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __format__(self, format_spec, /) | Return a formatted version of the string as described by format_spec. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(...) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __sizeof__(self, /) | Return the size of the string in memory, in bytes. | | __str__(self, /) | Return str(self). | | capitalize(self, /) | Return a capitalized version of the string. | | More specifically, make the first character have upper case and the rest lower | case. | | casefold(self, /) | Return a version of the string suitable for caseless comparisons. | | center(self, width, fillchar=' ', /) | Return a centered string of length width. | | Padding is done using the specified fill character (default is a space). | | count(...) | S.count(sub[, start[, end]]) -> int | | Return the number of non-overlapping occurrences of substring sub in | string S[start:end]. Optional arguments start and end are | interpreted as in slice notation. | | encode(self, /, encoding='utf-8', errors='strict') | Encode the string using the codec registered for encoding. | | encoding | The encoding in which to encode the string. | errors | The error handling scheme to use for encoding errors. | The default is 'strict' meaning that encoding errors raise a | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and | 'xmlcharrefreplace' as well as any other name registered with | codecs.register_error that can handle UnicodeEncodeErrors. | | endswith(...) | S.endswith(suffix[, start[, end]]) -> bool | | Return True if S ends with the specified suffix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | suffix can also be a tuple of strings to try. | | expandtabs(self, /, tabsize=8) | Return a copy where all tab characters are expanded using spaces. | | If tabsize is not given, a tab size of 8 characters is assumed. | | find(...) | S.find(sub[, start[, end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | format(...) | S.format(*args, **kwargs) -> str | | Return a formatted version of S, using substitutions from args and kwargs. | The substitutions are identified by braces ('{' and '}'). | | format_map(...) | S.format_map(mapping) -> str | | Return a formatted version of S, using substitutions from mapping. | The substitutions are identified by braces ('{' and '}'). | | index(...) | S.index(sub[, start[, end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Raises ValueError when the substring is not found. | | isalnum(self, /) | Return True if the string is an alpha-numeric string, False otherwise. | | A string is alpha-numeric if all characters in the string are alpha-numeric and | there is at least one character in the string. | | isalpha(self, /) | Return True if the string is an alphabetic string, False otherwise. | | A string is alphabetic if all characters in the string are alphabetic and there | is at least one character in the string. | | isascii(self, /) | Return True if all characters in the string are ASCII, False otherwise. | | ASCII characters have code points in the range U+0000-U+007F. | Empty string is ASCII too. | | isdecimal(self, /) | Return True if the string is a decimal string, False otherwise. | | A string is a decimal string if all characters in the string are decimal and | there is at least one character in the string. | | isdigit(self, /) | Return True if the string is a digit string, False otherwise. | | A string is a digit string if all characters in the string are digits and there | is at least one character in the string. | | isidentifier(self, /) | Return True if the string is a valid Python identifier, False otherwise. | | Call keyword.iskeyword(s) to test whether string s is a reserved identifier, | such as "def" or "class". | | islower(self, /) | Return True if the string is a lowercase string, False otherwise. | | A string is lowercase if all cased characters in the string are lowercase and | there is at least one cased character in the string. | | isnumeric(self, /) | Return True if the string is a numeric string, False otherwise. | | A string is numeric if all characters in the string are numeric and there is at | least one character in the string. | | isprintable(self, /) | Return True if the string is printable, False otherwise. | | A string is printable if all of its characters are considered printable in | repr() or if it is empty. | | isspace(self, /) | Return True if the string is a whitespace string, False otherwise. | | A string is whitespace if all characters in the string are whitespace and there | is at least one character in the string. | | istitle(self, /) | Return True if the string is a title-cased string, False otherwise. | | In a title-cased string, upper- and title-case characters may only | follow uncased characters and lowercase characters only cased ones. | | isupper(self, /) | Return True if the string is an uppercase string, False otherwise. | | A string is uppercase if all cased characters in the string are uppercase and | there is at least one cased character in the string. | | join(self, iterable, /) | Concatenate any number of strings. | | The string whose method is called is inserted in between each given string. | The result is returned as a new string. | | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs' | | ljust(self, width, fillchar=' ', /) | Return a left-justified string of length width. | | Padding is done using the specified fill character (default is a space). | | lower(self, /) | Return a copy of the string converted to lowercase. | | lstrip(self, chars=None, /) | Return a copy of the string with leading whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | partition(self, sep, /) | Partition the string into three parts using the given separator. | | This will search for the separator in the string. If the separator is found, | returns a 3-tuple containing the part before the separator, the separator | itself, and the part after it. | | If the separator is not found, returns a 3-tuple containing the original string | and two empty strings. | | removeprefix(self, prefix, /) | Return a str with the given prefix string removed if present. | | If the string starts with the prefix string, return string[len(prefix):]. | Otherwise, return a copy of the original string. | | removesuffix(self, suffix, /) | Return a str with the given suffix string removed if present. | | If the string ends with the suffix string and that suffix is not empty, | return string[:-len(suffix)]. Otherwise, return a copy of the original | string. | | replace(self, old, new, count=-1, /) | Return a copy with all occurrences of substring old replaced by new. | | count | Maximum number of occurrences to replace. | -1 (the default value) means replace all occurrences. | | If the optional argument count is given, only the first count occurrences are | replaced. | | rfind(...) | S.rfind(sub[, start[, end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | rindex(...) | S.rindex(sub[, start[, end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Raises ValueError when the substring is not found. | | rjust(self, width, fillchar=' ', /) | Return a right-justified string of length width. | | Padding is done using the specified fill character (default is a space). | | rpartition(self, sep, /) | Partition the string into three parts using the given separator. | | This will search for the separator in the string, starting at the end. If | the separator is found, returns a 3-tuple containing the part before the | separator, the separator itself, and the part after it. | | If the separator is not found, returns a 3-tuple containing two empty strings | and the original string. | | rsplit(self, /, sep=None, maxsplit=-1) | Return a list of the substrings in the string, using sep as the separator string. | | sep | The separator used to split the string. | | When set to None (the default value), will split on any whitespace | character (including \\n \\r \\t \\f and spaces) and will discard | empty strings from the result. | maxsplit | Maximum number of splits (starting from the left). | -1 (the default value) means no limit. | | Splitting starts at the end of the string and works to the front. | | rstrip(self, chars=None, /) | Return a copy of the string with trailing whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | split(self, /, sep=None, maxsplit=-1) | Return a list of the substrings in the string, using sep as the separator string. | | sep | The separator used to split the string. | | When set to None (the default value), will split on any whitespace | character (including \\n \\r \\t \\f and spaces) and will discard | empty strings from the result. | maxsplit | Maximum number of splits (starting from the left). | -1 (the default value) means no limit. | | Note, str.split() is mainly useful for data that has been intentionally | delimited. With natural text that includes punctuation, consider using | the regular expression module. | | splitlines(self, /, keepends=False) | Return a list of the lines in the string, breaking at line boundaries. | | Line breaks are not included in the resulting list unless keepends is given and | true. | | startswith(...) | S.startswith(prefix[, start[, end]]) -> bool | | Return True if S starts with the specified prefix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | prefix can also be a tuple of strings to try. | | strip(self, chars=None, /) | Return a copy of the string with leading and trailing whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | swapcase(self, /) | Convert uppercase characters to lowercase and lowercase characters to uppercase. | | title(self, /) | Return a version of the string where each word is titlecased. | | More specifically, words start with uppercased characters and all remaining | cased characters have lower case. | | translate(self, table, /) | Replace each character in the string using the given translation table. | | table | Translation table, which must be a mapping of Unicode ordinals to | Unicode ordinals, strings, or None. | | The table must implement lookup/indexing via __getitem__, for instance a | dictionary or list. If this operation raises LookupError, the character is | left untouched. Characters mapped to None are deleted. | | upper(self, /) | Return a copy of the string converted to uppercase. | | zfill(self, width, /) | Pad a numeric string with zeros on the left, to fill a field of the given width. | | The string is never truncated. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | maketrans(...) | Return a translation table usable for str.translate(). | | If there is only one argument, it must be a dictionary mapping Unicode | ordinals (integers) or characters to Unicode ordinals, strings or None. | Character keys will be then converted to ordinals. | If there are two arguments, they must be strings of equal length, and | in the resulting dictionary, each character in x will be mapped to the | character at the same position in y. If there is a third argument, it | must be a string, whose characters will be mapped to None in the result.
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
S.index(sottostringa) -> int
S
ci applico la funzionalita' index
che prende sottostringa
come argomento-> int
che indica la posizione trovata (oppure -1 se non c'è)# quindi possiamo fare
# nome vale 'andrea sterbini '
start = nome.index('drea')
start
False
nome[start:start+len('drea')] # [2,2+4)
'drea'
d | r | e | a | ---- | -- | -- | -- | 2 | 3 | 4 | 5 |
# mettendo tutto insieme
query = 'drea' # input dell'algoritmo
start = nome.index(query) # trovo il primo indice che contiene il contenut di QUERY
# sulla contenuto di NOME
end = start + len(query) # mi precalcolo indice di fine stringa
sub_name = nome[start:end] # faccio slicing della stringa
print(sub_name,start,end,nome) # stampo cosa ho trovato e dove, a partire da cosa
drea 2 6 andrea sterbini
d | r | e | a | ---- | -- | -- | -- | 2 | 3 | 4 | 5 |
nome[1:] # tutti i caratteri DOPO il
# primo (0 escluso, 1 compreso)
# 0 | 1-----------------
'ndrea sterbini'
nome[:2] # tutti i caratteri PRIMA
# del indice 2 escluso
# quindi solo carattere 0-th
# --0--1--| 2 3 4 5 6 7...
'an'
nome[-1] # al contrario di molti linguaggio a basso livello
# qui gli indici possono essere negativi
# il meno inverte la sequenza di lettura
# sto prendendo da 'andrea sterbini' <--- questa i finale
'i'
slicing
complessi perchè notazione è macchinosa (imho)nome = 'Python'
vuoto = nome[4:3] # ovviamente se start >= end, abbiamo stringa vuota
type(vuoto),vuoto
(str, '')
nome = 'Python'
vuoto = nome[-3:-4] # ovviamente se start >= end, abbiamo stringa vuota ''
type(vuoto),vuoto
(str, '')
nome = 'Python'
nome[-4:-3] == nome[2:3], nome[2:3]
# questo funzione seleziona il carattere 't' (un singolo carattere e' una stringa)
(True, 't')
nome = 'Python'
nome[-10:2], nome[3:100]
# se l'inizio è negativo e troppo grande si inizia dal primo carattere
# se la fine della slice è troppo grande si arriva all'ultimo
('Py', 'hon')
nome[-1000]
# MA ATTENZIONE: se invece indicizziamo il singolo carattere
# non possiamo chiedere più di -(len(nome)-1)
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_9389/137629210.py in <cell line: 1>() ----> 1 nome[-1000] 2 # MA ATTENZIONE: se invece indicizziamo il singolo carattere 3 # non possiamo chiedere più di -(len(nome)-1) IndexError: string index out of range
# Prendiamo tutti i caratteri in posizione multipla di 3
# il terzo valore indica come incrementare l'indice
nome[::3]
'Ph'
# prendiamoli in direzione opposta (incremento negativo)
nome[::-1]
'nohtyP'
# Risultati
'ippopotamo'[2:-2:2], 'BabbuINO'.lower()[-1:-10:-3]
('ppt', 'oua')
C
questa cosa non e' molto chiara perchè in C potete modificare direttamente le stringhe carattere per caratterenome = 'Python'
assumiamo io voglia modificare la P
di Python
in minuscola python
# in C potrei fare
nome[0] = 'p'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_9389/2897224970.py in <cell line: 2>() 1 # in C potrei fare ----> 2 nome[0] = 'p' TypeError: 'str' object does not support item assignment
In realta' non lo posso fare direttamente,
devo per forza creare un'altra stringa
A = nome.lower() # trasformo tutto in minnuscole
A
'python'
B = 'p'+nome[1:] # oppure faccio cut/paste
B
'python'
# con id(oggetto) posso capire se due cose sono lo stesso oggetto
id(A), id(B), id(A)==id(B)
# le due stringhe sono in posti diversi della memoria ?
(139845825377904, 139845815550896, False)
help(id)
Help on built-in function id in module builtins: id(obj, /) Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.)
Se dobbiamo scrivere testi che contengono accapi ('\n') possiamo usare il triplo apice '''
oppure il triplo doppio apice """
print("""
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
Possiamo costruire facilmente dei testi che contengono valori calcolati (ad es. presi da variabili)
f
(che sta per 'formatted'){espressione}
# definiamo le parti da interpolare nel testo
nome = 'Paolino'
cognome = 'Paperino'
indirizzo = 'Via dei Peri 32'
data = '29 febbraio'
orario = '20:30'
mittente = 'Gastone Paperone'
# e la lettera da spedire (che interpola semplici variabili)
lettera = f'''
Caro {nome} {cognome}
La invito al vernissage che si terrà a {indirizzo}
il giorno {data} alle ore {orario}
Cordialmente
{mittente}
'''
print(lettera)
Caro Paolino Paperino La invito al vernissage che si terrà a Via dei Peri 32 il giorno 29 febbraio alle ore 20:30 Cordialmente Gastone Paperone
from graphviz import Digraph
# Create Digraph object
figura = Digraph()
figura.body.append('''
graph [rankdir=LR]
node [shape=rect]
"namespace containing\n the variable (name)\nA" -> "RAM containing\n a reference to object" -> "RAM containing\n the object data"
''')
figura
## Ogni variabile è un nome contenuto in una tabella (namespace)
## che contiene un 'riferimento' all'oggetto in essa contenuto
Due oggetti possono essere abbastanza simili (se sono dello stesso tipo e contengono le stesse informazioni, sono interscambiabili)
Il confronto == torna True (uguaglianza dei contenuti)
Ma possono trovarsi in due aree di memoria diverse e quindi essere oggetti diversi (modificandone uno l'altro resta invariato)
Per distinguerli e sapere in qualche modo dove sono in memoria si usa la funzione id e per controllare se sono 'identici' si usa l'operatore is (identità)
# creiamo una stringa e copiamo la variabile A in B
A = 'Pippo e Pluto sono andati al mare con Minnie e Topolino'
B = A
# Se hanno lo stesso ID, di tratta dello stesso oggetto
print(id(A))
print(id(B))
A is B
139845815625952 139845815625952
True
from graphviz import Digraph
def show_vars( *variabili ):
grafo = Digraph()
grafo.body.append(f'''
graph [rankdir=LR]
node [shape=rect]''')
for nome in variabili:
valore = eval(nome)
grafo.body.append(f'''
{nome} -> "{id(valore)}" -> "{valore}"
''')
return grafo
show_vars( 'A', 'B' )
e contengono un riferimento (indirizzo) dell'oggetto in memoria
# esempio: assegnamento che cambia il riferimento
A = 78
A_prima = A
A = 'paperino'
A_dopo = A
print(id(A_prima))
print(id(A_dopo))
139846134631056 139845815881648
show_vars('A_prima')
show_vars('A_dopo')
# Esempio di un contenitore: una lista di oggetti eterogenei
L = [1, 'due', 3.5]
# ne copio il riferimento in una seconda variabile
M = L
# sono proprio la stessa cosa
print(id(L),id(M), L is M)
139845815559808 139845815559808 True
show_vars('M', 'L')
# modifico il contenuto a posizione 1 (secondo elemento, si conta da 0)
L[1] = 42
# si tratta sempre dello stesso oggetto sia in L che in M
print('identici?', L is M, '\nuguali?', L == M)
# ed è stato modificato il secondo elemento
print(L, M)
identici? True uguali? True [1, 42, 3.5] [1, 42, 3.5]
show_vars('M', 'L')
# ma se creo una lista con gli stessi dati
L = [1, 42, 3.5]
print('identici?', L is M, '\nuguali?', L == M)
show_vars('M')
identici? False uguali? True
show_vars('L')
attributi
)metodi
)int, str, bool, float, etc... sono oggetti
per scoprirne le caratteristiche usiamo help oppure ctrl-I in Spyder oppure . e l'autocompletamento
str # testo
int # interi # abs, mod, %, //
float # numeri con virgola
complex # numeri complessi # conjugate, imag, real, ...
bool # booleani (True, False)# and, or, not
from fractions import Fraction # frazioni intere
#help(Fraction)
f = Fraction(124,14) # denominator, numerator
f
Fraction(62, 7)
e che ne possono manipolare il contenuto o crearne di nuovi
Es. le operazioni su str
si usa la sintassi oggetto.nomedelmetodo(argomenti)
# Esempi
S = 'Paperino andò\t al, mare\n a nuotare'
# split (e varianti)
L = S.split()
# join
'|'.join(L)
S.lower()
# islower, isupper, isalpha, isnumeric
S.islower()
# upper, lower, title
S.upper()
# find
S.find('mare')
19
NOTA: le stringhe sono IMMUTABILI, ogni volta che ci fate operazioni sopra ne create una nuova
Python, invece che duplicarle, tiene copie uniche dei numeri piccoli e delle stringhe corte
B = 93
C = 92+1
print(id(B), id(C))
B is C
139846134631536 139846134631536
True
# per le stringhe l'ottimizzazione è applicata alle 'parole'
# che non contengono spazi (particolarmente importante nella
# ottimizzazione del codice in memoria)
S1 = 'giovanni' * 50
S2 = 'giovanni' * 50
print(id(S1), id(S2))
S1 is S2
139845825296944 139845825296944
True
# esempio di ottimizzazione dei piccoli numeri
esponente = 2
print((34**esponente) == ((30+4)**esponente), 'uguaglianza')
print((34**esponente) is ((30+4)**esponente), 'identità')
True uguaglianza False identità
'si comportano allo stesso modo' == 'hanno gli stessi metodi'
(MA NOTATE: metodi con nomi uguali potrebbero avere realizzazioni interne diverse)
E' quindi possibile costruire nuovi tipi di oggetti che si comportano in modo simile ad altri
i numeri interi e i float sono un esempio (e anche i razionali e i complessi)
(vedremo in seguito come farlo)
gli attributi (informazioni interne) degli oggetti in Python NON sono protetti
In altri linguaggi compilati (Java, C++) è possibile 'nascondere' le informazioni interne e fare in modo che solo i metodi dell'oggetto le possano manipolare
In Python (interpretato) questo non è possibile (o è stato scelto così)
Ma si è stabilito che per convenzione
TUTTI GLI ATTRIBUTI E METODI CHE INIZIANO CON '_' SONO PRIVATI
e non vanno letti o modificati o usati direttamente
(chi li ha inventati potrebbe benissimo modificarli in future versioni del programma)
quindi NON USATE MAI i metodi speciali :-)
(vedremo poi come definirli)
Esistono alcuni metodi speciali (che iniziano per __
) che realizzano le funzionalità degli operatori
usati nelle espressioni/istruzioni. Per es.
__eq__
che implementa l'operatore ==
__add__
che implementa l'operatore +
__mul__
che implementa l'operatore *
__len__
che implementa la funzione len
Tutti gli oggetti che implementano questi metodi possono essere confrontati, sommati, moltiplicati, contati, ...
Ecco come mai le stringhe possono essere sommate o moltiplicate, hanno un proprio metodo __add__
e __mul__
Questo vi sarà utile quando vedremo come costruire oggetti che possiamo confrontare sommare, o di cui vogliamo calcolare la lunghezza (se contengono elementi) ...
N = 3
N.__add__(5) # questo è cosa succede veramente se scrivo N + 5
8
# i numeri complessi hanno le 4 operazioni come gli altri numeri
# (ma sono implementate diversamente)
X_complesso = 3 + 2j # si usa j al posto di i=sqrt(-1)
Y_complesso = 7 - 6j
Z_complesso = X_complesso + Y_complesso # somma complessa
Z_complesso, Z_complesso.real, Z_complesso.imag
((10-4j), 10.0, -4.0)
def nome_della_funzione( argomenti ):
'docstring che descrive cosa fa'
istruzioni che calcolano il risultato
return risultato
Il corpo della funzione DEVE essere indentato (in genere di 4 spazi)
Gli argomenti
sono nomi che indicano le informazioni necessarie perchè la funzione possa svolgere il suo compito
NOTA: i nomi degli argomenti sono variabili disponibili SOLO nel corpo della funzione (la parte indentata)
Il risultato
è il dato che la funzione ha calcolato e che viene fornito al programma che la usa
# come si definisce la funzione
def media_altezze(altezze):
'calcolo la media di un gruppo di altezze' # docstring
somma_altezze = sum(altezze)
media_altezze = somma_altezze/len(altezze)
return media_altezze # valore risultante
## Come la si usa/chiama la funzione
# se abbiamo una lista di altezze
elenco_altezze = [ 170, 190, 165, 155, 186, 172, ]
# e ne calcoliamo la media chiamando la funzione 'media_altezze'
media = media_altezze(elenco_altezze) # e mettendo il risultato in una variabile
# otteniamo
media
173.0
altezze
(parametri formali, i dati che la funzione riceve da chi la chiama)elenco_altezze
Stile: è meglio usare nomi diversi per i parametri formali e per gli attuali per evitare di confondersi
calcola_altezza_media
pippo
altezze
lista
somma_altezze
sa
globale
: è il livello più esterno del vostro programma, in cui scrivete le istruzioni direttamente appoggiate al bordo sinistromodulo
: è il contenuto di un file importato con import
, ci trovate le variabili e le funzioni definite in quel file. Le ottenete scrivendo modulo.variabile
oppure modulo.funzione(argomenti)
locale
: ogni funzione usa delle variabili proprie, dette variabili locali, che sono accessibili SOLO nelle istruzioni del corpo
della funzione o di una sua sottofunzione. Gli argomenti della funzione sono anche loro variabili locali alla funzione.ATTENZIONE una variabile locale può nascondere una variabile globale
variabile = 42 # definisco una variabile globale
def funzione_di_prova( argomento ):
variabile = argomento # qui la ridefinisco come locale
print(variabile, 'stampo la locale')
print(variabile, 'globale')
funzione_di_prova(92)
print(variabile, 'globale invariata')
funzione_di_prova(667)
42 globale 92 stampo la locale 42 globale invariata 667 stampo la locale
Le variabili locali ad una funzione vengono CREATE nel momento in cui la funzione viene ESEGUITA (e non quando viene definita)
Ogni esecuzione crea un nuovo gruppo di variabili locali della funzione
Per cui le funzioni possono richiamare se stesse senza problemi, ciascuna chiamata userà uno spazio di memoria personale separato dagli spazi delle altre chiamate
Le variabili locali sono rilasciate quando si esce
dalla funzione e si torna al programma che l'ha chiamata
NOTA: la memoria che viene rilasciata è quella dei RIFERIMENTI.
Gli oggetti creati dalla funzione possono sopravviverle
MA QUESTO FA SPRECARE UN SACCO DI MEMORIA ???
NO, esiste un processo in background, il garbage collector che esamina la memoria continuamente e libera tutti gli oggetti che non sono più raggiungibili dai programmi in esecuzione
## Esempio di creazione di un oggetto dentro una funzione
def concatena(prima_parte, seguito):
# costruisco una nuova stringa
nuovo_testo = prima_parte + ' ' + seguito
return nuovo_testo # e la ritorno
A = 'inizio '
B = 'fine'
C = concatena(A, B)
print(A, B, C, sep='\n')
print(prima_parte)
# errore perchè 'nuovo_testo' non esiste nel namespace globale
inizio fine inizio fine
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_9389/2666591040.py in <cell line: 10>() 8 C = concatena(A, B) 9 print(A, B, C, sep='\n') ---> 10 print(prima_parte) 11 # errore perchè 'nuovo_testo' non esiste nel namespace globale NameError: name 'prima_parte' is not defined
and
, or
e not
not
ha priorità su and
che l'ha su or
E' quindi possibile scrivere condizioni complesse
piove = not soleggiato or strade_bagnate
porto_l_ombrello = piove or sole_abbacinante
strade_bagnate = ha_piovuto or innaffiamento_automatico_acceso
Per scegliere parti diverse di codice si usa l'istruzione if
e delle condizioni (booleane) che valgono True o False
Sintassi:
if condizione1:
istruzioni eseguite
se condizione1 è True
elif condizione2: # opzionale
istruzioni eseguite
se condizione1 è False e condizione2 è True
else: # opzionale
istruzioni eseguite
se condizione1 e condizione2 sono False
## Soluzioni
True and not False or True and False or not True
# è lo stesso che scrivere
(True and (not False) ) or (True and False) or (not True)
# cioè
(True and True) or False or False
True
# Visto che True == 1 e che False == 0
True+False/True+True*True-False
# è lo stesso che
1 + 0 / 1 + 1 * 1 - 0
# soluzione
is_raining = True
got_umbrella = False
have_money = True;
if not is_raining:
print('go out')
elif not got_umbrella and have_money:
print('buy umbrella and go out')
elif got_umbrella:
print('go out since got umbrella')
else:
print('stay home')