L.method() avec method = append, sort,index,reverse
Tuples:
-------
Un tuple est équivalent à une liste masi il n'est pas modifiable
T=(1,2,3)
T[1]
2
T[1]=5
TypeError: 'tuple' object does not support item assignment
Dictionnaires:
--------------
Tables non ordonnées de référence d'objets
D={}
D={'un': 1, "deux: 2}
D['un']
1
D.has_key('deux')
True
D.keys()
['un', 'deux']
D.values()
[1,2]
d[key] = value
Set d[key] to value.
del d[key]
Remove d[key] from d. Raises a KeyError if key is not in the map.
key in d
Return True if d has a key key, else False.
key not in d
Equivalent to not key in d.
iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).
clear()
Remove all items from the dictionary.
copy()
Return a shallow copy of the dictionary.
classmethod fromkeys(seq[, value])
Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
items()
Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.
keys()
Return a new view of the dictionary’s keys. See the documentation of view objects.
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
popitem()
Remove and return an arbitrary (key, value) pair from the dictionary.
popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
values()
Return a new view of the dictionary’s values. See the documentation of view objects.
Fonctions spéciales:
--------------------
lambda: fonction anonyme
f = lambda a, b: a + b
f(1,2)
3
apply: appelle des fonction avec des tuples en arguments
apply(f, (2,3)
5
map: applique une fonction à chaque objet d'une séquence
def m(x): return x*2
map(m,[0,2,4]
[0, 4, 8]
print: écrit sur la sortie standard
print "Class" + "Foo"
ClassFoo
print
print "Class %s is not = %d" % ('Foo', 1)
Class Foo is not = 1
print "Class %s is not = %d" % ('Foo', 1),
Classes et espace de nom (namespace):
-------------------------------------
import: récupère l'intégralité d'un module
from: récupère certains noms d'un module
reload: recharge le module modifié
Notion importante lorsque l'on travaille dans l'interpréteur (python ou ipython)
L'import charge et exécute la première fois le code du module (fichier)
> cat simple.py
print "Hello"
spam = 1
>>> import simple # importe charge et exécute la première fois le code du module
Hello
>>> simple.spam # l'affectation a créé un attribut
1
>>> simple.spam = 2 # change l'attribut dans le module
>>> import simple # récupère le module déjà chargé
>>> simple.spam # le code n'a pas été exécuté de nouveau
2
Classe Foo déclarée dans un module foo, soit un fichier foo.py
import foo
f=foo.Foo()
from foo import Foo
f = Foo()
Les fonctions définies dans les classes ne sont accéssibles que via une instance
a=Foo()
a.dummy()
Foo().dummy()
Avec python, un attribut d'instance (membre) est une simple variable et existe
dès qu'on lui affecte une valeur.
class Foo:
def foo(self,value):
self.attribut = value
return self.attribut
Foo().foo(5)
5
Cet attribut peux également être initialisé (par défault) à la création de
l'instance par le constructeur __init__ (méthode appelée à la création d'un
objet)
class Foo:
def __init__(self,value=0):
self.attribut = value
def __repr__(self):
return "%d" % self.attribut
a=Foo()
a
0
a=Foo(5)
a
5
Attribut de classe
class Foo:
foo = const
Attribut d'instance
class Foo:
__init__(self, value)
self.foo = value
En interne python associe les appels des méthodes d'instances aux méthodes de