en and fr python3 courses

This commit is contained in:
gwen
2018-08-21 10:25:44 +02:00
parent 8c6997b27d
commit ee81eaad1b
228 changed files with 49353 additions and 0 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,4 @@
# Sphinx build info version 1
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
config: ae2abe7703a46685be1c606e20366209
tags: 645f666f9bcd5a90fca523b33c5a78b7

View File

@ -0,0 +1,190 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Les design patterns &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="La librairie standard" href="stdlib.html" />
<link rel="prev" title="Le style de programmation par exceptions" href="exceptions.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="stdlib.html" title="La librairie standard"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="exceptions.html" title="Le style de programmation par exceptions"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="les-design-patterns">
<h1>Les design patterns<a class="headerlink" href="#les-design-patterns" title="Lien permanent vers ce titre"></a></h1>
<p>Les design patterns <strong>ne sont pas</strong> indépendants du langage.
Ils dépendent de limplémentation.</p>
<div class="section" id="le-duck-typing">
<h2>Le duck typing<a class="headerlink" href="#le-duck-typing" title="Lien permanent vers ce titre"></a></h2>
<p>En python, le duck typing est une forme extreme de programmation par interface.
Ne pas hériter dans des directions fausse</p>
<p>exemple : une voiture ne peut hériter dun moteur, parce que un moteur nest pas une voiture.</p>
</div>
<div class="section" id="hold-or-wrap">
<h2>hold or wrap ?<a class="headerlink" href="#hold-or-wrap" title="Lien permanent vers ce titre"></a></h2>
<p><strong>hold</strong>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">O</span><span class="o">.</span><span class="n">S</span><span class="o">.</span><span class="n">method</span><span class="p">()</span>
</pre></div>
</div>
<p>Cela induit un couplage fort (cf la loi de Demeter)</p>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">law of Demeter : never more than one dot.</p>
</div>
<p>wrap : a hold by private name, with a:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">S</span><span class="o">.</span><span class="n">method</span><span class="p">()</span>
</pre></div>
</div>
<p>Ou bien une méthode getattr:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="fm">__getattr__</span><span class="p">()</span>
</pre></div>
</div>
<p>Gets coupling right.</p>
</div>
<div class="section" id="wrapper-can-restrict-inheritance-cannot-restrict">
<h2>wrapper can restrict, inheritance cannot restrict<a class="headerlink" href="#wrapper-can-restrict-inheritance-cannot-restrict" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">RestrictingWrapper</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">w</span><span class="p">,</span> <span class="n">block</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_w</span> <span class="o">=</span> <span class="n">w</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_block</span> <span class="o">=</span> <span class="n">block</span>
<span class="k">def</span> <span class="nf">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_block</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">AttributeError</span><span class="p">,</span> <span class="n">n</span>
<span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_w</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="pattern-de-creation-singleton">
<h2>Pattern de création : singleton<a class="headerlink" href="#pattern-de-creation-singleton" title="Lien permanent vers ce titre"></a></h2>
<p># utiliser un module au lieu dune classe</p>
<p>in <cite>toto.py</cite>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Toto</span><span class="p">()</span>
<span class="n">toto</span> <span class="o">=</span> <span class="n">Toto</span><span class="p">()</span>
</pre></div>
</div>
<p>in another module:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">toto</span> <span class="k">import</span> <span class="n">toto</span>
</pre></div>
</div>
</div>
<div class="section" id="la-factory">
<h2>la factory<a class="headerlink" href="#la-factory" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">load</span><span class="p">(</span><span class="n">pkg</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
<span class="n">m</span> <span class="o">=</span> <span class="nb">__import__</span><span class="p">(</span><span class="n">pkg</span><span class="p">,</span> <span class="p">{},</span> <span class="p">{},</span> <span class="p">[</span><span class="n">obj</span><span class="p">])</span>
<span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="n">obj</span><span class="p">)</span>
<span class="bp">cls</span> <span class="o">=</span> <span class="n">load</span><span class="p">(</span><span class="s1">&#39;p1.p2.p3&#39;</span><span class="p">,</span> <span class="s1">&#39;c4&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="template-method-self-delegation">
<h2>template method (self delegation)<a class="headerlink" href="#template-method-self-delegation" title="Lien permanent vers ce titre"></a></h2>
<p># Abstract base class:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">OrganiseMethod</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">org_method</span><span class="p">():</span>
<span class="k">def</span> <span class="nf">do_this</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">do_that</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">Concrete</span><span class="p">(</span><span class="n">OrganiseMethod</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">do_this</span><span class="p">():</span> <span class="o">...</span>
<span class="k">def</span> <span class="nf">do_that</span><span class="p">():</span> <span class="o">...</span>
</pre></div>
</div>
<p>il est préférable de lever une NotImplementedError, ce qui revient à faire
une classe abstraite.</p>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="stdlib.html" title="La librairie standard"
>suivant</a> |</li>
<li class="right" >
<a href="exceptions.html" title="Le style de programmation par exceptions"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,73 @@
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""Command line interpreter
"""
import cmd
# ____________________________________________________________
# this Cli is a model of a basic use of a simple cmd
class Cli(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.doc_header = "Documented commands (type help <command>):"
self.undoc_header = "Undocumented commands"
self.prompt = "#Prompt> "
self.intro = """cli (command line interpreter)
(type help or ? for commands list)"""
self.ruler = "-"
def emptyline(self):
print "Type 'exit' to finish withe the session or type ? for help."
def default(self, line):
print "unknown command prefix"
print "*** unknown syntax : %s (type 'help' for help for a list of valid commands)"%line
self.emptyline()
def do_exit(self, line):
"""Exits from the console"""
return True
def do_quit(self, line):
return True
def do_EOF(self, args):
"""Exit on system end of file character"""
return True
# ____________________________________________________________
# commands pre and post actions
# def precmd(self, line):
# return line
# def postcmd(self, stop, line):
# # if there is a problem, just return True : it stops everythings
# stop = True
# return stop # quit if stop == True
# ____________________________________________________________
# program pre and post actions
# def preloop(self):
# # action for the beginning of the program
# pass
# def postloop(self):
# # action for the end of the program
# print "exit cli"
# ____________________________________________________________
class HelloCli(Cli):
def input_hello(self, line):
return line.replace(",", " and ")
def output_hello(self, result):
print result
def do_hello(self, line):
self.output_hello("hello, " + self.input_hello(line))
#return False # if you want to stay into the cli
return True # if you want to exit
if __name__ == '__main__':
prompt = HelloCli()
prompt.cmdloop("intro, modifies Cmd.intro")

View File

@ -0,0 +1,10 @@
def helloworld(ob):
print "Hello world"
return ob
@helloworld
def myfunc():
print "my function"
myfunc()
print myfunc

View File

@ -0,0 +1,28 @@
class Turbo(object):
def turbo(self):
return "VRRRRROUUUMMM"
class Prix(object):
def get_prix(self):
raise NotImplementedError
class Voiture(Prix, Turbo):
def __init__(self, constructeur, vitesse_max=160):
self.constructeur = constructeur
self.vitesse_max = vitesse_max
def roule(self):
return "vroummm"
def signaletique(self):
return "constructeur : {0}, vitesse_max {1}".format(self.constructeur,
self.vitesse_max)
class DoDoche(Voiture):
def get_prix(self):
return "4000"
def achete_voiture(voiture):
if not hasattr(voiture, "get_prix"):
raise TypeError("pas le bon type")
return "prix de la voiture: {0} euros".format(voiture.get_prix())

View File

@ -0,0 +1,20 @@
liste = ['blah', 'blih', 'bluh']
iterateur = liste.__iter__()
print iterateur.next()
print iterateur.next()
print iterateur.next()
print iterateur.next()
#Traceback (most recent call last):
# File '<stdin>', line 1, in <module>;
#StopIteration
class Iterateur:
i = 0
def next(self):
if self.i <= 10: raise StopIteration
self.i += 1
return 2**self.i
def __iter__(self): return self
iterateur = Iterateur()
for i in iterateur: print i

View File

@ -0,0 +1,18 @@
class NotFoundError(Exception):
pass
class MaClasse:
pass
class MaClasseDeux:
pass
binding = dict(un=MaClasse, deux=MaClasseDeux)
def ma_factory(key):
if key in binding:
return binding[key]()
else:
return NotFoundError("keskece?")

View File

@ -0,0 +1,28 @@
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point to
# it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full
# path to your home directory.
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
readline.read_history_file(histfile)
except IOError:
pass
import atexit
atexit.register(readline.write_history_file, histfile)
del os, histfile
# enhanced completion
#import rlcompleter2
#rlcompleter2.setup()

View File

@ -0,0 +1,22 @@
class Wrap(object):
def __init__(self, name, wrap):
self.slots = ('_name', '_w')
self._name = name or "wrapped_element"
self._w = wrap
def __getattr__(self, name):
if name in self.slots:
return getattr(self, name)
else:
return getattr(self._w, name)
# def get_w(self, name):
# return getattr(self._w, name)
# def set_w(self, name, value):
# return setattr(self._w, name, value)
# _w = property (get_w, set_w)
def __repr__(self):
return "[W_Element %s]"% repr(self._name)

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

View File

@ -0,0 +1,94 @@
Les design patterns
=====================
Les design patterns **ne sont pas** indépendants du langage.
Ils dépendent de l'implémentation.
Le duck typing
-------------------
En python, le duck typing est une forme extreme de programmation par interface.
Ne pas hériter dans des directions fausse
exemple : une voiture ne peut hériter d'un moteur, parce que un moteur n'est pas une voiture.
hold or wrap ?
--------------
**hold**::
O.S.method()
Cela induit un couplage fort (cf la loi de Demeter)
.. important:: law of Demeter : never more than one dot.
wrap : a hold by private name, with a::
self.S.method()
Ou bien une méthode getattr::
__getattr__()
Gets coupling right.
wrapper can restrict, inheritance cannot restrict
--------------------------------------------------
::
class RestrictingWrapper(object):
def __init__(self, w, block):
self._w = w
self._block = block
def __getattr__(self, n):
if n in self._block:
raise AttributeError, n
return getattr(self._w, n)
Pattern de création : singleton
-------------------------------
# utiliser un module au lieu d'une classe
in `toto.py`::
class Toto()
toto = Toto()
in another module::
from toto import toto
la factory
--------------
::
def load(pkg, obj):
m = __import__(pkg, {}, {}, [obj])
return getattr(m, obj)
cls = load('p1.p2.p3', 'c4')
template method (self delegation)
---------------------------------
# Abstract base class::
def OrganiseMethod()
def org_method():
def do_this()
def do_that()
def Concrete(OrganiseMethod)
def do_this(): ...
def do_that(): ...
il est préférable de lever une NotImplementedError, ce qui revient à faire
une classe abstraite.

View File

@ -0,0 +1,452 @@
Définir et manipuler des classes
=================================
.. glossary::
objet
Un object est une entité possédant un type, un état, et un comportement.
Un object correspondant généralement à une entité du monde réel, mais
cette entité peut être abstraite.
On parle aussi d'**instance**.
**état d'un objet** : ensemble de propriétés auxquelles sont associées des
valeurs.
Les variables de l'objet sont appelées des **attributs**.
le comportement d'un :term:`objet` :
- des actions effectuées sur l'objet
- des appels faits sur l'objet
envois de messages à l'objet = appel de **méthodes**
programmation objet (première approche)
-----------------------------------------
- le type et le protocole d'un objet sont définis par sa classe
- une classe possède un ensemble d'attributs et de méthodes
deux relations possibles
~~~~~~~~~~~~~~~~~~~~~~~~~
.. glossary::
heritage
relation "est une espèce de " utilisée entre une classe et une autre classe
instantiation
relation "est une instance de " entre un objet et une classe
- est une instance de (objets par rapport à classe)
- est une espèce de (classe par rapport à classe, :term:`heritage`)
**instance**
- définition d'une classe
- instance de classe : on peut créer des objets à partir d'un type "classe"
(une classe est instanciable)
>>> class A:
... pass
...
>>> a = A()
:term:`heritage` : notation en python
>>> class A: pass
...
>>> class B(A): pass
...
>>> b = B()
>>> type(b) == B
>>> isinstance(b, A) == True
possibilité en python d'héritage multiple::
class A(B, C): pass
attribut d'objets et de classes
----------------------------------
>>> o = object()
>>> o
<object object at 0x7f77c9cda0d0>
>>> class C(object): pass
...
>>> class C: pass
...
>>> c = C()
>>> c.a = 3
>>> c.a
3
>>> vars(c)
{'a': 3}
>>> c.__dict__
{'a': 3}
>>> C.__dict__
{'__module__': '__main__', '__doc__': None}
>>> C.c = 5
>>> C.__dict__
{'c': 5, '__module__': '__main__', '__doc__': None}
>>> c.c
5
>>> c.z = 3
>>> c.z
3
>>> c.__dict__
{'a': 3, 'z': 3}
>>> C.__dict__
{'c': 5, '__module__': '__main__', '__doc__': None}
>>> class MaKlass:
... def unefonction(self, x):
... print x
...
>>> MaKlass.__dict__
{'__module__': '__main__', '__doc__': None, 'unefonction': <function unefonction at 0x7f77c5b0c488>}
>>> k = MaKlass()
>>> k.__dict__
{}
>>> def autrefonc(self, x)
File "<stdin>", line 1
def autrefonc(self, x)
^
SyntaxError: invalid syntax
>>> def autrefonc(self, x):
... print x
...
>>> k.autrefonc = autrefonc
>>> k.__dict__
{'autrefonc': <function autrefonc at 0x7f77c5b0c500>}
>>> MaKlass.__dict__
{'__module__': '__main__', '__doc__': None, 'unefonction': <function unefonction at 0x7f77c5b0c488>}
>>> MaKlass.unefonction(k, "toto")
toto
>>> k.unefonction("toto")
toto
>>> k.__dict__
{'autrefonc': <function autrefonc at 0x7f77c5b0c500>}
>>> MaKlass.toto = "test"
>>> k.__dict__
{'autrefonc': <function autrefonc at 0x7f77c5b0c500>}
>>> k.toto
'test'
>>>
le __dict__ avec l'héritage de classe
-------------------------------------------
>>> class A(object): pass
...
>>> A.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'A' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
>>> class B(A):
... b = 3
...
>>> class C(B):
... c = 2
...
>>> c = C()
>>> o = C()
>>> o.__dict__
{}
>>> o.c
2
>>> o.b
3
>>> o.__class__
<class '__main__.C'>
>>> o.__class__.__dict__
dict_proxy({'__module__': '__main__', 'c': 2, '__doc__': None})
>>>
method resolution object
-----------------------------
>>> class A(object): pass
...
>>> A.__mro__
(<class '__main__.A'>, <type 'object'>)
>>> class B(A): pass
...
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
>>> class C(A, B): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases A, B
>>>
introspection contre encapsulation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
voir un objet comme un espace de nommage. C'est plus **agile**.
attributs et méthodes vus comme des ajouts dans l'espace de nommage
>>> a.a = 2
>>> def function(x):
... print x
...
>>> a.f = function
>>> a.f("hello")
hello
>>>
la nécessité d'un design objet
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
affichage d'une calculette, il faut créer un type `Touche`
qui contient deux désignations : `Chiffre` et `operation`::
type operation = Plus | Moins | Divise
type touche = Chiffre of int | Memoire | Op of operation
soit, on définit un type touche, soit on ne définit pas ce type::
type operation = Plus | Moins | Divise
type memoire = Memoire
type chiffre = Chiffre
- les structures de données (int, str, list, dict...) : types de base
- les structures de données utilisateur : les classes !
.. function:: type (objname)
:param objname: l'objet dont on veut connaître le type
Manipulations sur les classes et les objets
---------------------------------------------
En python un type et une classe c'est la même chose. Une classe
est un type standard. En python tout est objet, et tout provient d'un seul objet
(qui s'appelle ``object``).
- encapsulation (cacher les attributs (variables d'état)) d'un objet.
- interfaces : chaque aspect d'une classe peut être vu comme une interface.
Une interface décrit un ensemble de comportements.
on peut considérer une interface comme un protocole d'utilisation d'un objet
dans un contexte donné.
on peut alors créer des outils qui sauront traiter n'importe quel objet
pourvu qu'il respecte une ensemble d'interfaces.
.. todo:: travailler l'héritage, l'aggrégation, la délégation
Voici un exemple de classe `Voiture` :
.. literalinclude:: snippets/heritage.py
:pyobject: Voiture
j'instancie ma classe `Voiture` :
>>> ma_voiture = Voiture("ma_marque", "150km/h")
>>> ma_voiture.roule()
'vroummm'
>>> ma_voiture.signaletique()
'constructeur : ma_marque, vitesse_max 150km/h'
.. todo:: faire des traitements dans l'init
- héritage (est une sorte de)
- polymorphisme : un objet apparait comme une instance d'une classe parente
.. literalinclude:: snippets/heritage.py
:pyobject: Turbo
>>> v = DoDoche("marque", 160)
>>> v.get_prix()
'7000'
>>> isinstance(v, Prix)
True
>>>
mais l'objet conserve son identité :
>>> type(v)
<type 'Voiture'>
la fonction ``achete_voiture()`` sera appelée indépendamment du type de l'objet,
du moment que l'objet a une méthode `get_prix()`, c'est le duck typing, qu'il
est préférable de ramener au polymorphisme d'objet, ou bien utiliser les :mod:`abc`
(abstract base classes).
.. literalinclude:: snippets/heritage.py
:pyobject: achete_voiture
tout le code :
.. literalinclude:: snippets/heritage.py
:download:`télécharger le code <snippets/heritage.py>`
- **l'aggrégation**
un attribut est lui-même un objet (ce qui est fréquent en python)...
.. literalinclude:: snippets/aggregation.py
- **la délégation**
la fonction "property" est un élément du design de python lui-même
.. function:: property()
les patrons de conception
---------------------------
- le patron **factory**
.. literalinclude:: snippets/patrons.py
:download:`télécharger usine (factory) <snippets/patrons.py>`
- le patron **wrapper**
:download:`télécharger wrapper <snippets/wrap.py>`
.. literalinclude:: snippets/wrap.py
exemple d'utilisation de `Wrap()`
>>> class O:
... pass
...
>>> o = O()
>>> o.a = "blah"
>>>
>>> from wrap import Wrap
>>> w = Wrap("monwrap", o)
>>> w._name
'monwrap'
>>> w._w
<__main__.O instance at 0x7fbf177aaa28>
>>> w._w.a
'blah'
>>> w.a
'blah'
>>> w.u
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "wrap.py", line 11, in __getattr__
return getattr(self._w, name)
AttributeError: O instance has no attribute 'u'
>>>
- le patron de conception **itérable**
:download:`télécharger iterable <snippets/iterable.py>`
.. literalinclude:: snippets/iterable.py
- le patron **decorateur**
:download:`télécharger decorateur <snippets/decorateur.py>`
.. literalinclude:: snippets/decorateur.py
>>> def deco(func):
... func.attr = 'decorated'
... return func
...
>>> @deco
... def f(): pass
...
>>> f.attr
'decorated'
>>>
autre exemple : les méthodes statiques
>>> class A(object):
... @staticmethod
... def my_class_method(cls):
... # do stuff here
métaclasses
-----------------
>>> class A:
... pass
...
>>> type(A)
<type 'classobj'>
>>> class B(object): pass
...
>>> type(B)
<type 'type'>
>>> help(type)
>>> C = type('C', (), {})
>>> C
<class '__main__.C'>
>>>
>>> type(object)
<type 'type'>
>>> type(type)
<type 'type'>
>>> isinstance(type, object)
True
>>> isinstance(object, type)
True
>>>
::
class MaMetaClasse(type):
"""Exemple d'une métaclasse."""
def __new__(metacls, nom, bases, dict):
"""Création de notre classe."""
print("On crée la classe {}".format(nom))
return type.__new__(metacls, nom, bases, dict)
class MaClasse(object):
__metaclass__ = MaMetaClasse
exemple : forcer l'implémentation d'un singleton avec les métaclasses
::
class Singleton(type):
instance = None
def __call__(cls, *args, **kw):
if not cls.instance:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class ASingleton(object):
__metaclass__ = Singleton
a = ASingleton()
b = ASingleton()
assert a is b
print(a.__class__.__name__, b.__class__.__name__)
class BSingleton(object):
__metaclass__ = Singleton
c = BSingleton()
d = BSingleton()
assert c is d
print(c.__class__.__name__, d.__class__.__name__)
assert c is not a

View File

@ -0,0 +1,52 @@
Sphinx et docutils
=====================
Docutils
------------
Il y a des librairies de bas niveau qui permettent de générer de l'odt, je pense à pyUNO, ou bien ezodf_
.. _ezodf: https://pythonhosted.org/ezodf/
A l'opposé, il y a des librairies de très haut niveau intégré à des chaînes de documentation avec des sources en xml, des modèles documentaires, des chartes graphiques, etc. Par exemple, scenari_
.. _scenari: http://scenari-platform.org/projects/scenari/fr/pres/co/
Un juste milieu est la très intéressante librairie docutils_ :
.. _docutils: http://docutils.sourceforge.net/
Il s'agit d'une libairie python très utilisée dans le monde python (par exemple, la documentation officielle python est rédigée en `syntaxe docutils`_).
.. _`syntaxe docutils` : http://docutils.sourceforge.net/docs/index.html
C'est une `syntaxe wiki`_ assez puissante, un sur-ensemble de la très connue syntaxe markdown.
.. _`syntaxe wiki`: http://docutils.sourceforge.net/docs/user/rst/quickref.html
Pour l'installer::
apt-get install python-docutils
Il y a plusieurs utilitaires : ``rst2html``, ``rst2*``, l'utilitaire que je te conseille est : ``rst2odt``.
Pour l'usage de `rst2odt`_ c'est simple, on part d'un fichier texte formaté en restructured text::
rst2odt fichier.txt > fichier.odt
Et voilà simple, pratique, efficace.
.. _`rst2odt`: http://docutils.sourceforge.net/docs/user/odt.html
C'est l'outil que nous utilisons en priorité. Voici un exemple d'usage avancé avec l'utilisation d'un modèle::
rst2odt --create-links --file-insertion-enabled --raw-enabled --endnotes-end-doc \
--stylesheet=styles/styles.odt --custom-odt-footer="XXXREMPLACEHEADERXXX" \
DossierCommercial.rst > DossierCommercial.odt
La documentation technique
-----------------------------
L'outil sphinx_
.. _sphinx: http://sphinx-doc.org/

View File

@ -0,0 +1,246 @@
.. default-role:: literal
Le style de programmation par exceptions
========================================
.. glossary::
Exception
Les exceptions permettent de récupérer des situations où le calcul ne peut pas se poursuivre.
Dans ces cas, un récupérateur d'exceptions permet de continuer le calcul
sachant qu'une des branches a échoué.
Exemple d':term:`exception`
>>> assert 2 == 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
La règle du samouraï
----------------------
.. important:: règle du Samouraï : une fonction doit renvoyer le résultat escompté
ou bien lever une exception
>>> def function_raise(x):
... if not type(x) == int:
... raise TypeError("Pas le bon type")
... else:
... return x + 1
...
>>> try:
... e = function_raise("une string")
... except TypeError, e:
... print e
...
Pas le bon type
>>
- la fonction doit renvoyer des valeurs du même type (ou bien ``None``)
- la fonction doit lever une exception appropriée
utiliser la pile d'appel pour débugger
---------------------------------------
Utiliser la pile d'appels, elle se lit de bas en haut. Il est possible de
provoquer cette pile d'appels.
::
import traceback
traceback.print_exc()
.. todo:: s'exercer à lire une pile d'appels un peu complexe.
Traiter une exception avec
::
try:
...
except:
import traceback
traceback.print_exc()
else:
bla bla
finally:
bla bla
.. attention:: ne **jamais** briser la pile d'appels sans savoir précisément
ce que l'on fait, et remonter une autre exception
Exemple :
>>> def function(x):
... if x == 1: raise TypeError("pas le bon type")
... else: return "ok"
...
>>> def function2(x):
... try:
... return "c'est " + function(x)
... except TypeError, e:
... raise AssertionError("on a une autre exception là")
...
>>> try:
... function2(1)
... except Exception, e:
... print e
...
on a une autre exception là
>>>
Le raise (ou le re-raise) est souvent utilisé pour lever une exception métier
et cacher une exception système de bas niveau.
exemple::
try:
add_s(dn, listdata)
except ldap.LDAPError, err:
raise MyOwnError(msg + str(err))
except Exception:
pass
.. todo:: dans quel cas entrons-nous dans le `else` ? dans le `finally` ?
.. todo:: créer des exceptions métier
exemple d'exceptions *dans la vraie vie*::
"user defined exceptions"
# Exceptions for an Option
class PropertiesOptionError(AttributeError):
"attempt to access to an option with a property that is not allowed"
def __init__(self, msg, proptype):
self.proptype = proptype
super(PropertiesOptionError, self).__init__(msg)
#____________________________________________________________
# Exceptions for a Config
class ConfigError(Exception):
"""attempt to change an option's owner without a value
or in case of `_cfgimpl_descr` is None
or if a calculation cannot be carried out"""
pass
class ContextError(Exception):
"""context needed but not given
"""
pass
class ConflictError(Exception):
"duplicate options are present in a single config"
pass
#____________________________________________________________
# miscellaneous exceptions
class RequirementError(Exception):
"""a recursive loop occurs in the requirements tree
requires
"""
pass
class SlaveError(Exception):
"problem with a slave's value length"
pass
class ConstError(TypeError):
"no uniq value in _NameSpace"
pass
Créer le plus possible ses propres exceptions spécifiques au programme
La programmation par exception peut vite devenir un style de programmation
très utilisé. C'est assez agréable mais le réserver pour la gestion d'une situation
particulière, que ça reste une intervention pour les cas non gérés par le programme
(en général).
Les exceptions imbriquées
--------------------------------
>>> try:
... ma_func()
... except TypeError, e:
... do_something()
... except Exception, e:
... do_somethin_else()
...
Exemple de programme utilisant massivement la programmation par exceptions :
`tiramisu`_
.. _tiramisu: http://tiramisu.labs.libre-entreprise.org/
La hiérarchie des exceptions
-----------------------------
Extrait de la documentation officielle::
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning

View File

@ -0,0 +1,20 @@
Liste des exercices
--------------------
Voici la liste des liens vers les différents exercices de la formation.
.. todolist::
exercices à faire
--------------------
- implémenter un script qui lit les arguments de la ligne de commande et qui les écrit sur la sortie standard
- implémenter les sous-classes de shape point et cercle, calculer le périmètre.
- itérer sur une liste et récupérer la valeur maximum de cette liste (la fonction builtin *max*)
>>> a = [3,8,3,5,9,1,4]
>>> max(a)
9

View File

@ -0,0 +1,126 @@
.. default-role :: literal
Prise en main
==============
L'objectif de ce cours est de vous apprendre à programmer en
:term:`python`. Ce cours a été fait avec :term:`sphinx`, l'outil de
gestion de documentation en python utilisé pour documenter python lui-même.
Pour plus d'information : :doc:`docutils`
Avec python :
- vous n'avez pas grand chose à savoir pour arriver à faire beaucoup de choses,
- vous allez pouvoir travailler de manière
- entièrement autonome
- rapide
- agile (au sens des méthodes agiles)
- vous allez progresser rapidement
- aucune connaissance préalable en programmation n'est requise
- le hello world en une ligne::
python -c "print 'hello'"
- rendre un fichier exécutable et ajouter le she bang::
#!/usr/bin/env python
print "hello"
.. note:: lorsqu'on lance python sur un programme, des fichiers
avec une extension `.pyc` apparaissent.
.. glossary::
python
python_ est un langage de programmation généraliste, libre, totalement
orienté objet, dynamiquement typé, semi-interprété ou, pour certaines
utilisations optimisées, compilé ou compilé à la volée (JIT).
sphinx
sphinx_ est un outil de documentation utilisant la syntaxe wiki
docutils_
- lorsqu'on lance python sans spécifier de nom de fichier, c'est l'interpréteur
python qui est lancé (le "prompt")
En python, le dicton le plus répandu est "there must be an obvious way
to do it", (il y a certainement une manière évidente de le faire en
python), ``import this`` permet de se remémorer les
dictons de python. Ce dicton est très différent de l'approche du perl
par exemple, qui présuppose : "there is more than one way to do it",
c'est-à-dire que en gros en perl, on peut le faire n'importe comment,
mais pas en python, enfin en python c'est pas conseillé de le faire à sa
sauce, il y a en général une bonne pratique à découvrir et à mettre en place.
Taper "python" dans votre console
::
>>> print "hello world"
hello world
::
>>> import this
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
...
.. seealso::
les modules, :ref:`namespaces` et la librairie standard
:doc:`stdlib`
pour avoir de l'aide, taper dans le prompt :
>>> help(function)
Le bon réflexe de chercher ce qui est le plus répandu et le plus utilisé est le
bon en python : on dit que python est livré "batteries included", ce qui
signifie que lorsqu'on a un besoin précis il faut chercher dans la librairie
standard python, puis dans les librairies les plus utilisées en python, puis en
dernier... le reste, ce qui est disponible. Mais si une librairie connue ne
fait pas exactement ce qui est attendu et qu'une libraire inconnue du bataillon
fait exactement ce qui est attendu, (et a l'air de fonctionner
correctement...), alors il faut choisir la libraire inconnue au bataillon.
usage de python
------------------
à peu près tous les domaines de l'informatique, du scripting système à la génération
de pdf en passant par le développement web et le développement rapide d'applications.
exemple : web server
pour créer un serveur web simplement::
python -m server.http 8000 localhost
exemple : utiliser python pour faire un fichier de conf
::
spam = "eggs"
actions = [
('call_view', 'com.next')
]
.. _python: http://www.python.org
.. _sphinx: http://sphinx.pocoo.org
.. _docutils: http://docutils.sf.net

View File

@ -0,0 +1,41 @@
Apprentissage de la programmation avec python
----------------------------------------------
.. toctree::
:maxdepth: 2
getting-started
settings
type
structures
testsunitaires
docutils
Programmation python, connaissances de base
--------------------------------------------
.. toctree::
:maxdepth: 2
classes
prompt
specialmethods
exceptions
DesignPatterns
stdlib
Récapitulatifs de la formation
---------------------------------
.. toctree::
:maxdepth: 1
exercices
Index et recherche
-------------------
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -0,0 +1,58 @@
Bonjour à toute la promo,
Comme convenu, voici quelques liens (algorithmiques et autres)
D'abord, python :)
https://www.python.org/
et le tuto dive into python
http://www.diveintopython3.net/
et le fameux python challenge
http://www.pythonchallenge.com/
c'est un challenge algorithmique qu'on peut résoudre avec du python mais pas forcément, on peut utiliser n'importe quel langage.
Ceux qui dépasseront la sixième étape (sans regarder les soluces) auront droit à mon respect :)
Ensuite, la librairie pandas que nous avons vue :
http://pandas.pydata.org/
et pandas sur python-simple
http://www.python-simple.com/python-pandas/stacking-unstacking-dataframe.php
Sinon après il y a plein de livres, notamment le wikilivre
https://fr.wikibooks.org/wiki/Programmation_algorithmique/Sommaire
https://fr.wikibooks.org/wiki/Cat%C3%A9gorie:Programmation_algorithmique_(livre)
https://fr.wikibooks.org/wiki/Programmation
après sur wikipédia il y a plein de pages consacrée à divers algorithmes (le voyageur de commerce, les algoritmes tirés de la biologie, etc...) mais on n'a pas vu ça en détails.
après il y a une bonne présentation des modules et sous-modules (mais c'est de l'ocaml)
https://www.good-eris.net/formation-ocaml/modules/submod.html
vous pouvez aussi vous y mettre :
https://www.good-eris.net/formation-ocaml/intro.html
un très bon livre pour ocaml
http://programmer-avec-ocaml.lri.fr/chap10.html
de très bon livres pour apprendre le python existent aussi, notamment ceux de Tarek Ziadé (un français qui habite en Bourgogne).
Voilà
Très bonne continuation à vous tous, à bientôt
Gwen

View File

@ -0,0 +1,107 @@
Interactions avec l'utilisateur
===============================
les prompts
--------------
`raw_input` ou `input`
(raw_input renvoie une string, input essayes d'évaluer, soyez prudent...)
>>> from subprocess import call
>>> filename = input("quel fichier voulez-vous afficher ?\n")
>>> call("cat " + filename, shell=True)
.. _cmdlabel:
le module :mod:`cmd` et les interpréteurs
--------------------------------------------
le monde des interpréteur ligne de commande...
Peu après l'âge de bronze vint le temps de l'interpréteur ligne de commande,
c'est-à-dire quelque chose de plus spécifique que **l'application ligne de commande**,
ou que l'utilitaire ligne de commande.
Un interpréteur ligne de commande est un programme qui :
- est forcément plein texte
- vous donne un prompt
- prends toutes ses entrées d'un coup
- produit une sortie (typiquement des lignes de texte)
- vous redonne un prompt
Le shell unix est un bon exemple d'interpréteur ligne de commande.
Un utilitaire ligne de commande est un programme unix-like qui prend toutes
les entrées d'un coup, et qui vous renvoie une sortie d'un coup.
le module :mod:`cmd` : exemple d'utilisation
.. module:: cmd
:synopsis: interpréteur ligne de commande
.. literalinclude:: snippets/cli.py
:download:`telecharger cmd <snippets/cli.py>`
::
>>> from cli import Cli
>>> prompt = Cli()
>>> prompt.cmdloop()
cli (command line interpreter)
(type help or ? for commands list)
#Prompt> ?
Documented commands (type help <command>):
==========================================
EOF exit
Undocumented commands:
======================
cmd help quit
#Prompt>
pour ajouter une commande, utiliser simplement l'héritage::
>>> from cli import Cli
>>> class Prompt(Cli):
... def do_hello(self, line):
... print "hello %s", line
...
>>> prompt = Prompt()
>>> prompt.cmdloop()
cli (command line interpreter)
(type help or ? for commands list)
#Prompt> ?
Documented commands (type help <command>):
==========================================
EOF exit
Undocumented commands:
======================
cmd hello help quit
#Prompt> hello world
.. todo:: faire un petit projet d'interpréteur ligne de commande du jeu C+/C-
lire et écrire dans un fichier
-------------------------------
les **handle de fichier** (file handles)
>>>
>>> fh = file('test', 'w')
>>> fh.write('hello world')
>>> fh.close()
>>> content = file('test', 'r').read()
>>> content
'hello world'
>>>

View File

@ -0,0 +1,220 @@
.. default-role:: literal
Mettre en place son environnement de travail
=============================================
Les éditeurs pour python
-----------------------------
N'importe quel éditeur qui respecte les coding standards du pep8 convient :
https://www.python.org/dev/peps/pep-0008/
pep8_
.. _pep8: https://pep8.org/
d'une manière générale, de base un éditeur spartiate peut convenir du moment
que l'intentation de 4 espaces est respectée et que les tablulations sont
remplacées par des espaces, car le plus important en python c'est l'indentation,
et le fait de bien voir ou est le règlage de l'encodage (ça doit être en ``utf-8``)
Pour voir si ton éditeur est bien configuré, tu prends n'importe quel fichier python
que tu as créé, puis tu faire un ::
pep8 <mon_fichier.py>
et `pep` va dire ce qui ne va pas en termes de syntaxe.
IDLE
------
https://docs.python.org/2/library/idle.html
Pour information, IDLE est un éditeur intégré (dans la lib standard de python)
mais je te le déconseille (trop spartiate).
un framework de développement intégré : :term:`IDLE`
.. glossary::
IDLE
IDLE_ est un IDE (environnement de développement intégré) mis à disposition
dans la :term:`librairie standard` de python
.. _IDLE: http://docs.python.org/2/library/idle.html
nano
--------
pour l'exemple, avec **nano**, voici comment faire une config qui permette
de coder en python. On configure nano avec le ``.nanorc``
Exemple de ``.nanorc`` ::
# replace les tabulations par 4 espaces
set tabsize 4
set tabstospaces
# indente automatiquement
set autoindent
# la touche home renvoie en debut de code
set smarthome
# ne met pas de retour chariot a la fin d'une ligne
# si elle depasse la largeur du terminal
set nowrap
unset softwrap
# chargement de plusieur fichiers
set multibuffer
# coloration syntaxique
## Python
#include "/usr/share/nano/python.nanorc"
Gedit
---------
Gedit c'est très bien pour coder en python, mais de base c'est pas sur un serveur,
il faut pouvoir être en mode graphique.
Il faut règler l'indentation à 4 espaces pour respecter le pep8.
Et règler le replacement des tablulations par des espaces.
Mais surtout, très vite il faut installer les paquets additionnels, notamment
pour que gedit supprime les espaces en fin de ligne par exemple.
Je l'utilise souvent mais il faut des plugins avec
genre ceux-ci (si tu es sur ubuntu)::
apt-get install gedit-plugins
dans ce paquet par exemple, l'outil pour commenter-décommenter le code est intéressant
(sélection d'un paragraphe, puis Ctrl-M)
tu peux régler après la complétion des parenthèses, etc.
il y a aussi le paquet developer plugins :
https://apps.ubuntu.com/cat/applications/gedit-developer-plugins/
Après avec les plugins gedit commence à bien tenir la route.
Vi
----------
Toujours la même problématiques (espaces, tablulation...)
Donc voici une partie de ``.vimrc`` qui le fait::
"Pour le collage"
set pt=<F5>
set vb t_vb="
set shiftwidth=4
set expandtab
set ts=4
set sw=4
syntax on
filetype indent on
filetype plugin on
set autoindent
set hlsearch " Surligne les resultats de recherche
set wrap " Pas de retour a la ligne auto (affichage)
set showmatch " Affiche parenthese correspondante
set softtabstop=4 " Largeur d'une tabulation
"set fdm=indent " Repli selon l'indentation
maintenant après il y a un python-mode assez avancé qui permet de faire pas mal de choses.
(valider avec la syntaxe avec pylint, valider le pep8...)
Mais il faut une config plus avancée.
D'une manière générale, il y a la possibilité de valider avec des outils externes (pylint, pychecker, pep8...) et il y a aussi la possibilité de valider tout ça dans un éditeur.
configurer son éditeur : résumé
-----------------------------------
- les fichiers sources ont l'extension `.py`
- une instruction par ligne
- les blocs sont marqués par l'indentation (utilser 4 espaces), règler
l'éditeur pour transformer les tabulations en espaces
configurer son prompt python
-------------------------------
.. envvar:: PYTHONPATH
pointe par défaut sur le répertoire courant, il est possible d'ajouter
un path
à mettre dans votre `.bashrc` :
::
export PYTHONPATH:`pwd`
export PYTHONPATH=$PYTHONPATH:'/usr/share':'/toto/titi/tata'
alias pyenv='export PYTHONPATH=`pwd`:$PYTHONPATH'
export PYTHONSTARTUP='/home/gwen/.pystartup'
.. envvar:: PYTHONSTARTUP
les trucs à mettre dans vos pytstartups (comme dans vos .bashrc)
- autocomplétion
- affichage de l'historique
exemple de `.pystartup`
à télécharger ici : :download:`snippets/pystartup`
::
# Store the file in ~/.pystartup, and set an environment variable to point to
# it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full
# path to your home directory.
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
readline.read_history_file(histfile)
except IOError:
pass
import atexit
atexit.register(readline.write_history_file, histfile)
del os, histfile
# enhanced completion
#import rlcompleter2
#rlcompleter2.setup()
Consulter la librairie standard
-------------------------------------
.. glossary::
librairie standard
Une des règles de base de python est qu'il existe certainement une manière
conseillé de faire une tâche en python. Le premier réflexe est d'aller
voir dans la `librairie standard`_
.. _`librairie standard`: http://docs.python.org/2.7/library/index.html
Premier réflexe : la doc en ligne ou bien installée sur votre disque dur.
la page d'accueil de la doc officielle python :
.. image:: images/DocPython.png
et surtout, une fois la librairie standard abordée, la page d'index des
modules :
.. image:: images/ModuleIndex.png

View File

@ -0,0 +1,250 @@
Programmation python courante
================================
.. _namespaces:
les espaces de nommage
-----------------------
L'espace de nommage le plus courant est l'organisation en modules et en packages.
Packages et modules::
package/
__init__.py
module1.py
subpackage/
__init__.py
module2.py
A utilser pour organiser votre projet
Permet de minimiser les risques de conflits de nome
Permet de diminuer les entrées dans le :envvar:`PYTHONPATH`
::
import package.module1
from package.subpackage import module2
from package.subpackage.module2 import name
- le fichier `__init__.py`
- `reload(module)` au prompt
- dangereux : l'import "*", utiliser l'attribut spécial `__all__` pour l'import
sélectif
::
from os import *
lance un module en tant que script :
::
if __name__ == "__main__":
main()
Organisation modulaire
- construire des composants élémentaires
- combiner ces composants
- utiliser une structure pyramidale : les composants sont les éléments de
composants plus complexes.
- découplage de l'ensemble en composants indépendants (gros programmes réalisables)
- donner de la structure (rendre les gros programmes compréhensibles)
- spécifier les liens entre les composants (rendre les programmes maintenables)
- identifier les sous-composants indépendants (rendre les programmes réutilisables)
- forcer l'abstraction (augmenter la sureté du programme)
modules chargés et modules importés
--------------------------------------
Les modules susceptibles d'être chargés sont dans le :envvar:`PYTHONPATH`.
Mais comment peut-on savoir ou ils sont physiquement (sur le disque dur) ?
.. envvar:: `sys.modules`
>>> 'twisted' in sys.modules
False
>>> import twisted
>>> 'twisted' in sys.modules
True
>>> sys.modules['twisted']
<module 'twisted' from '/usr/lib/python2.7/dist-packages/twisted/__init__.pyc'>
>>>
.. attention:: un module présent dans `sys.modules` n'est pas forcément importé
dans l'espace de nommage usuel. Il faut importer le module pour
pouvoir l'utiliser.
>>> sys.modules['email']
<module 'email' from '/usr/lib/python2.7/email/__init__.pyc'>
>>> dir(email)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'email' is not defined
>>>
Pour récupérer le chemin du module
.. code-block:: python
print(os.path.abspath(<module>.__file__))
Pour importer un module qui n'est pas dans le `sys.path`
.. code-block:: python
fch = open('/path/to/mymodule/custom.py', 'r')
my_module = imp.load_module('dhcp_custom', fch, '/path/to/mymodule.py', ('.py', 'U', 1))
Connaître la version d'un module
-------------------------------------
Exemple : le module ``datetime``
C'est suivant la version de python car c'est la librairie standard.
Sinon, en général il y a un attribut __version__
>>> import sqlalchemy
>>> sqlalchemy.__version__
'0.9.8'
>>>
Les méthodes spéciales
-----------------------
méthodes spéciales correspondants aux interfaces des types de bases :
.. function:: __init__(self, *args, **kwargs)
le constructeur de l'instance d'objet
.. function:: __add__(self, other)
correspond à la notation `+`
exemple :
.. literalinclude:: snippets/specialmethods.py
>>> from specialmethods import *
>>> z = Zone("titi", 10)
>>> z2 = Zone("tutu", 40)
>>> z > z2
False
>>> z + z2
<specialmethods.Zone object at 0x7f02d95fb190>
>>> z3 = z + z2
>>> z3.name
'tititutu'
>>> z3.level
50
>>>
Attributs et accesseurs
---------------------------
python est un langage à attributs, c'est-à-dire que le protocole d'accès
aux attributs est règlable.
>>> class C(object):
... classattr = "a class attribute"
...
>>> cobj = C()
>>> cobj.classattr
'a class attribute'
>>> cobj.insattr = "an instance attribute"
>>> cobj.insattr
'an instance attribute'
>>> C.__dict__['classattr']
'a class attribute'
>>> cobj.__dict__['insattr']
'an instance attribute'
les attributs ne sont pas systématiquement encapsulées en python.
pour contrôler l'accès aux attributs, on utilise les méthodes spéciales::
__getattr__(self, name)
__setattr__(self, name, value)
class AnObject(object):
......
def __setattr__(self, name, val):
if name == 'src': #do something
# this will assign the real object.name,
#despite __setattr__
self.__dict__[name]=val
def __getattr__(self, name):
# ...
try:
func = getattr(obj, "method")
except AttributeError:
... deal with missing method ...
else:
result = func(args)
func = getattr(obj, "method", None)
if callable(func):
func(args)
- un **attribut** spécial : `__slots__`
permet de fixer les attributs possibles d'une classe
::
>>> class Bar(object):
... __slots__ = ("a","b","c")
...
>>> b = Bar()
>>> b.a = "toto"
>>> b.a
'toto'
>>> b.d = "titi"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Bar' object has no attribute 'd'
les slots
~~~~~~~~~~~
.. important:: l'encapsulation n'est pas une condition de base de la programmation
par objects, surtout que le contrôle nuit à l'agilité.
>>> class Point(object):
... __slots__ = 'x', 'y'
...
>>> p = Point()
>>> p.x = 2
>>> p.y = 3
>>> p.z = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Point' object has no attribute 'z'
>>>
- notation `|` et notation `>`
::
class Test:
nombre = 1
def __or__(self, other):
return self.nombre + other.nombre
def __lshift__(self, other):
self.nombre = self.nombre + other.nombre
t1 = Test()
t2 = Test()
t2.nombre = 2
print t1 | t2
t1 << t2
print t1.nombre

View File

@ -0,0 +1,210 @@
La :term:`librairie standard`
================================
les builtins
-------------
.. module:: builtins
:synopsis: les fonctions directement à disposition sans import spécifique
- le module :mod:`builtins`, tout ce qui est accessible directement
>>> dir('__builtins__')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '_formatter_field_name_split', '_formatter_parser',
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
>>>
- le module :mod:`subprocess`, appels systèmes
.. module:: subprocess
:synopsis: exécuter une commande shell, récupérer le code retour et la sortie
.. function:: subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)¶
>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1
.. function:: subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)¶
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
>>> subprocess.check_output("exit 1", shell=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
- le module :mod:`sys`, paramètres et fonctions systèmes
.. module:: sys
:synopsis: paramètres et fonctions systèmes
.. envvar:: sys.argv
la ligne de commande
.. function:: sys.exit()
terminer un programme
.. envvar:: sys.path
ce qu'il y a dans le :envvar:`PYTHONPATH`
.. module:: optparse
:synopsis: parsing de la ligne de commande
- le module :mod:`optparse` pour faire des outils ligne de commande
module plus récent : argparse
.. literalinclude:: snippets/cmdline.py
- les modules de tests unitaires :mod:`unittest` et :mod:`doctests`
.. module:: unittest
:synopsis: module de tests unitaires
.. module:: doctest
:synopsis: module de tests unitaires basé sur les docstrings
- le module :mod:`xml.etree` pour parser du xml
::
tree = xml.parse("testFile.xml")
rootElement = tree.getroot()
bookList = rootElem.findall("Books")
if bookList != None:
for book in bookList:
#faire quelque chose avec les livres
- le module :mod:`urllib` pour parser les urls et les manipuler (`urllib2`)
.. module:: urllib
:synopsis: parse des urls
.. function:: urllib.urlopen(url)
lit une url distante
.. module:: time
:synopsis: caculs de temps
- :mod:`time` pour la manipulation de temps
::
t1 = time.clock()
# Do Stuff Here
t2 = time.clock()
print t2 - t1
**now**
::
import time
now = time.localtime(time.time())
dateStr = time.strftime("%A, %B %d, %Y, %I:%M %p", now)
print dateStr
.. module:: getpass
:synopsis: recupération des mots de passe en ligne de commande
- le module :mod:`getpass` pour gérer les motes de passe
>>> import getpass
>>> p = getpass.getpass()
Password:
>>> p
'toto'
>>>
.. module:: shelve
:synopsis: linéarisation de données
- linéarisation de données
>>> import shelve
>>> shelve.open("database", 'c')
{}
>>> s = shelve.open("database", 'c')
>>> s
{}
>>> s["o"] = ('a', 'b', 'c')
>>> s.cl
s.clear s.close
>>> s.cl
s.clear s.close
>>> s.close()
>>>
.. module:: abc
:synopsis: les abstract base classes
- le module :mod:`abc` pour faire des interfaces propres
.. function:: abc.register(subclass)
exemple
::
from abc import ABCMeta
class MyABC:
__metaclass__ = ABCMeta
MyABC.register(tuple)
assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
.. module:: hotshot
:synopsis: benchmark
- le module :mod:`hotshot` benchmark
::
import hotshot
prof = hotshot.Profile('toto.txt')
prof.runcall(make_description)
prof.close()
- un exemple de librairie externe : :mod:`IPy`
.. module:: IPy
:synopsis: traitement des ips en python < python 3.3 remplacé par ipadress
::
sudo apt-get install python-ipy
::
from IPy import IP
try:
ipy = IP('{0}/{1}'.format(ip, mask), make_net=True)
except ValueError:
print "marche pas"
network = ipy.net()
broadcast = ipy.broadcast()
return broadcast, network

View File

@ -0,0 +1,205 @@
.. default-role:: literal
Structures de contrôle et fonctions
====================================
- tests
>>> if "a":
... print "a"
...
a
>>> if "":
... print "hell"
...
>>> a = 2
>>> if a == 1:
... print "un"
... else:
... print "deux"
...
deux
>>>
.. important:: les types de base ont tous une valeur booléenne
- itérations
>>> for i in range(10):
... print i
...
0
1
2
3
4
5
6
7
8
9
>>>
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- tant que
>>> i = 10
>>> while i != 0:
... print i
... i = i -1
...
10
9
8
7
6
5
4
3
2
1
>>>
fonctions
-----------
>>> def blabla(x):
... """fonction qui printe"""
... print x
...
>>>
il n'y a que des fonctions (et pas de procédures):
>>> def ma_func(x):
... "écrit quelque chose dans un fichier"
...
>>> ma_func("a")
>>> print ma_func("a")
None
>>>
est équivalent à :
>>> def ma_func(x):
... "écrit quelque chose dans un fichier"
... return None
- arité d'une fonction:
- paramètre non nommé
- paramètre nommé
>>> def ma_fonction(*args, **kwargs):
... print "arguments : ", str(args)
... print "argumments nommés", str(kwargs)
...
>>> ma_fonction("toto", "titi", tutu=2, tata=3)
arguments : ('toto', 'titi')
argumments nommés {'tata': 3, 'tutu': 2}
>>>
- signature d'une fonction : ça peut renvoyer n'importe quoi (tout ce qu'on veut)
:term:`return` ou :term:`yield` ?
.. glossary::
yield
permet de renvoyer le résultat d'une fonction en plusieurs étape
à l'aide d'un générateur
return
résultat d'une fonction
>>> def ma_fonction():
... for i in range(10):
... yield i
...
>>> for i in ma_fonction():
... print i
...
0
1
2
3
4
5
6
7
8
9
>>>
- espaces de nommage à l'intérieur d'une fonction :
>>> def toto(x):
... print vars()
...
>>> toto("sdfsdf")
{'x': 'sdfsdf'}
>>> class A(object):pass
...
>>> a = A()
>>> a.a = "titi"
>>> a.b = "toto"
>>> vars(a)
{'a': 'titi', 'b': 'toto'}
puisque tout est objet en python, ``vars(mon_objet)`` est équivalent à
``mon_objet.__dict__``
- générateurs et compréhension de liste
les compréhensions de listes permettent de générer de nouvelles listes
exemple :
>>> [ 2*i for i in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
>>> [x for x in range(10) if x>5]
[6, 7, 8, 9]
>>>
>>> [(i, j) for i in range(2,5) for j in range (4,8)]
[(2, 4), (2, 5), (2, 6), (2, 7), (3, 4), (3, 5), (3, 6), (3, 7), (4, 4), (4, 5), (4, 6), (4, 7)]
>>>
les expressions générateurs
>>> expr = (2*i for i in range(10))
>>> expr
<generator object <genexpr> at 0x7ff9efa77cd0>
>>> for e in expr:
... print e
...
0
2
4
6
8
10
12
14
16
18
>>>
le polymorphisme paramétrique
-----------------------------
polymorphisme exemple de contexte :
la fonction print
>>> print 1
1
>>> print "1"
1
.. todo:: `print 1` et `print "1"` renvoient le même résultat. Pourquoi ?

View File

@ -0,0 +1,122 @@
Tests unitaires et pile d'appels
=================================
Les tests automatiques sont un complément à la déclaration des types.
que tester, quoi tester ?
- que les composants interagissent bien entre eux
- que les unités (fonctions, objets...) réagissent bien à une entrée spécifique
- que le code se comporte de la manière attendue dans des environnements différents
(systèmes d'exploitation, etc...)
les types de tests :
- tests unitaires
- tests fonctionnels
- tests d'acceptation
- tests d'intégration
Quel outil utiliser ?
- la :doc:`stdlib` propose le module :mod:`unittest` et unittest2.
.. module:: py.test
:synopsis: outil de test unitaires de la pylib
- :mod:`py.test` est **le plus simple** (plus simple que unittest)
http://pytest.org/latest/
::
def test_simple():
"test si ma_fontion renvoie bien 3"
assert ma_fontion(2) == 3
- `py.test` utilise `assert` et `raises`
- `unittest` necessite de faire sytématiquement une classe, puis `assertEqual()`
- :mod:`doctest` est plus simple mais charge trop les docstrings
.. todo:: écrire un test unitaire avec `py.test` pour la fonction suivante
- installer le paquet `python-pytest`
- écrire un fichier avec une fonction dedans
::
def double(x):
return x*2
- écrire un fichier commençant par `test_` qui teste les fonctions du fichier
options utiles dans `py.test`
------------------------------
::
py.test --tb=no
py.test --tb=short
py.test -x (dernière erreur)
py.test -s (c'est comme nocapture en fait)
py.test -x --nocapture --pdb
py.test -xl --pdb
py.test -k test_simple
utiliser le module :mod:`pdb`
.. module:: pdb
:synopsis: debugger de la lib standard
::
import pdb
pdb.set_trace()
depuis py.test :
::
import pytest
def test_function():
...
pytest.set_trace() # invoke PDB debugger and tracing
Remarquons que :mod:`pdb` utilise le module :mod:`cmd`, voir :ref:`cmdlabel` qu'on a déjà vu précedemment
::
(Pdb) h
Documented commands (type help <topic>):
========================================
EOF bt cont enable jump pp run unt
a c continue exit l q s until
alias cl d h list quit step up
args clear debug help n r tbreak w
b commands disable ignore next restart u whatis
break condition down j p return unalias where
Miscellaneous help topics:
==========================
exec pdb
Undocumented commands:
======================
retval rv
(Pdb)
last but not least :
utiliser pylint ou pychecker
::
apt-get install pylint

View File

@ -0,0 +1,662 @@
.. default-role:: literal
.. default-domain: python
Typage, types de base
======================
python est un langage dynamiquement typé. qu'est-ce que cela signifie ?
- pas de déclaration des types (attention différent de l'inférence de types): les variables n'ont pas
de type fixé, ce qui signifie que le type est fixé au moment de l'affectation
(pendant le rutime).
- pas de déclaration des variables (une variable est créée au moyen de la première
affectation).
.. todo:: créer une variable
>>> a = 3
>>> a
3
.. todo::
- ouvrir l'interpréteur python
- dans la console créer un objet de type integer, float, string, liste, dictionnaire
- vérifier les types à l'aide de la fonction
- vérifier que en python tout est objet
- type de base et types conteneurs
- types mutables et types immutables
>>> a = 2
>>> b = 3
>>> b = 5
>>> a
2
>>> b
5
>>> l = ['a', 'b', 'c', 'd']
>>> p = [l, 'e']
>>> p
[['a', 'b', 'c', 'd'], 'e']
>>> l = ['i', 'j']
>>> p
[['a', 'b', 'c', 'd'], 'e']
>>> l
['i', 'j']
.. todo:: jouer avec les types
- l'interpréteur python comme calculette, les opérations numériques
>>> x = 1
>>> y =2
>>> x > y
False
>>> x == y
False
>>> x != y
True
- l'interpréteur pour manipuler les strings
>>> s = "bla bla"
'bla bla'
>>> s = 'bla bla'
'bla bla'
>>> s = " 'bli bli' "
>>> s
" 'bli bli' "
>>> s = """ sdfsdf "bla bla" sdfsdf"""
>>> s
' sdfsdf "bla bla" sdfsdf'
>>>
>>> s = "bla bla"
>>> m = "hu hu"
>>> s + m
'bla blahu hu'
>>> m * 3
'hu huhu huhu hu'
>>>
>>> len(m)
5
>>>
>>> m[3]
'h'
>>> m[3:5]
'hu'
>>>
>>> s = "ssdfsdf {0} sdfsdfsdf {1}".format("blah", "blih")
>>> s= 'a'
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> t = "abc"
>>> t.startswith("a")
True
>>> l = ['a', 'b', 'c']
>>> "-".join(l)
'a-b-c'
>>>
.. todo:: lower(), upper(), strip(), title()
.. todo: recherche et remplacement dans une string
index(), find(), replace()
- le module :mod:`regexp`
.. module:: regexp
:synopsis: expression régulières
>>> import re
>>> s = "sdf dfdfdf blah bla df"
>>> re.findall(r'\w*', s)
['sdf', '', 'dfdfdf', '', 'blah', '', 'bla', '', 'df', '']
>>> re.findall(r'df*', s)
['df', 'df', 'df', 'df', 'df']
>>>
unicode
------------
En python 2.X : deux types : `str` et `unicode` (en python 3 ces types sont unifiés)
on peut facilement tomber sur des erreurs unicode::
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0:
ordinal not in range(128)
- l'encodage (unicode):
on part d'un objet unicode :
>>> u = u"éèà bla"
>>> u
u'\xe9\xe8\xe0 bla'
on le transforme en string utf-8 :
>>> u.encode("utf-8")
'\xc3\xa9\xc3\xa8\xc3\xa0 bla'
>>> print u.encode("utf-8")
éèà bla
>>>
on peut partir d'une string en utf-8, puis::
manips importantes de traitement unicode (si on n'est pas en python 3)
>>> u = u"ésdsfè"
>>> u
u'\xe9sdsf\xe8'
>>> print u
ésdsfè
>>> str(u)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0:
ordinal not in range(128)
>>> u.encode("utf-8")
'\xc3\xa9sdsf\xc3\xa8'
>>> s = u.encode("utf-8")
>>> type(s)
<type 'str'>
>>>
Il faut utiliser ``.encode()``, et pas ``.decode()``::
if type(s) == unicode #types.UnicodeType:
bla bla
if type(s) == str:
rien à faire
manipulations diverses :
- enlever les accents
>>> import unicodedata
>>> s = u"un été même pas chaud"
>>> import unicodedata as U
>>> s2 = ''.join(U.normalize('NFD', x)[0] for x in s)
>>> s2
u'un ete meme pas chaud'
>>>
- enlever la ponctuation
>>> import re
>>> import string
>>> rgx = re.compile('[%s]' % string.punctuation)
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
tuples, listes, dictionnaires
---------------------------------
>>> t = (1,2,3)
>>> l = [1,2,3]
>>> d = {'a': 2, 'b':3, 'c':4}
>>>
>>> l = ['e','p','q','t']
>>> l.pop()
't'
>>> l
['e', 'p', 'q']
>>> l
['e', 'p', 'q']
>>> l.pop(1)
'p'
>>> l
['e', 'q']
>>>
exercice
-------------
écrire la string "1-2-3-4-5-6-7-8-9" programmatiquement
>>> [str(i) for i in l]
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> l2 = []
>>> for i in l:
... l2.append(str(i))
...
>>> l2
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>>
>>> l = range(1,9)
>>> l2 = [str(i) for i in l]
>>> "-".join(l2)
'1-2-3-4-5-6-7-8'
>>> s= "-"
>>> l2.extend(range(20))
>>> l2
['1', '2', 'sdfsdf', '3', '4', '5', '6', '7', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l + l2
[1, 2, 3, 4, 5, 6, 7, 8, '1', '2', 'sdfsdf', '3', '4', '5', '6', '7', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l.extend(l2)
KeyboardInterrupt
>>> l = []
>>> l = list()
>>> list
<type 'list'>
>>> list()
[]
>>> list(range(2))
[0, 1]
>>> tuple
<type 'tuple'>
>>> t = (1,2,3)
>>> t
(1, 2, 3)
>>> list(t)
[1, 2, 3]
>>> t
(1, 2, 3)
>>> type(t)
<type 'tuple'>
>>>
.. important:: utiliser get plutôt que l'accès par items lorsque l'on n'est pas sûr
::
>>> d = {}
>>> d.get('toto')
>>> d['toto'] ='titi'
>>> d.get('toto')
'titi'
>>> print d.get('toto')
titi
>>> print d.get('to')
None
>>> d['tot']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'tot'
>>>
KeyboardInterrupt
>>>
>>> x=dict(a=23,b=45,c=67,d=89)
>>> x
{'a': 23, 'c': 67, 'b': 45, 'd': 89}
>>> y=dict.fromkeys(range(4), 'ho')
>>> y
{0: 'ho', 1: 'ho', 2: 'ho', 3: 'ho'}
# and a new method to fetch-and-remove an item, by key:
>>> x.pop('c')
67
>>> x
{'a': 23, 'b': 45, 'd': 89}
>>> x.pop('z')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'z'
>>> x.pop('z', 55)
55
>>> for x in enumerate('ciao'): print x
...
(0, 'c')
(1, 'i')
(2, 'a')
(3, 'o')
>>>
.. module:: collections
:synopsis: autres types de données
- le module :mod:`collections` :
- `OrderedDict`, `defaultdict`
remarques sur les tuples
>>> 1,
(1,)
>>> (1,)
(1,)
>>> (1)
1
>>> ()
()
>>> tuple()
()
>>> value = 1,
>>> value
(1,)
.. todo:: addition de listes, append, tranches, tri de listes
::
def remove_duplicates(lst):
...
l = [4, 7, 30, "hello", 7, "world", 30, 7]
remove_duplicates(l)
assert l == [4, 7, 30, "hello", "world"]
.. todo:: defaultdict, get (avec une valeur par défaut)
- tri de liste personnalisé :
.. literalinclude:: snippets/sorter.py
>>> 'a' in d
True
>>> t[1]
2
>>>
>>> for i in l:
... print i
...
1
2
3
>>>
>>> for i in d:
... print i
...
a
c
b
>>>
>>> for key, value in d.items():
... print key, " : ", value
...
a : 2
c : 4
b : 3
>>>
.. todo:: l'interpréteur python pour l'introspection des objets
en python, **pas besoin de déclaration de type**. Qu'est-ce que ça veut dire ?
>>> type(1)
<type 'int'>
>>>
>>> dir(3)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__',
'__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__',
'__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__',
'__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__',
'__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__',
'__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__',
'__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__',
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
'__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',
'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
>>>
>>> type(3)
<type 'int'>
>>>
- Le type set
Set
collection non ordonnées d'éléments uniques
- le type set immutable et le type set mutable.
- un ensemble peut être étendu ou bien seulement englobé
::
Manipulations non supportées
>>> e["a"]
Traceback (most recent call last):
TypeError: unsubscriptable object
>>> e.append("a")
Traceback (most recent call last):
AttributeError: 'Set' object has no attribute 'append'
Création
Ensemble vide :
::
>>> e = set()
>>> e
Set([])
>>> e = set("toto")
>>> e
Set(['t', 'o'])
>>> d = {"a":1,"b":2}
>>> f = set(d)
>>> f
Set(['a', 'b'])
Appartenance et définition en extension
::
Set(['a', 'b'])
>>> "a" in i
True
>>> len(h)
4
>>> for u in h:
... print u
...
a
b
t
o
>>> e.add("a")
>>> e
Set(['a'])
>>> for i in range(5):
... e.add(i)
...
>>> e
Set(['a', 0, 2, 3, 4, 1])
Set(['a'])
>>> e.add("b", "c")
Traceback (most recent call last):
TypeError: add() takes exactly 2 arguments (3 given)
>>> for i in range(5):
... e.add(i)
...
>>> e
# Suppression :
>>> f = e.copy()
>>> f
Set(['a', 0, 2, 3, 4, 1])
>>> f.remove(0)
Opérations sur les ensembles
::
>>> v = sets.Set()
>>> e.issubset(f)
False
>>> f.issubset(e)
True
>>> e.issuperset(f)
True
>>> f &lt; e
True
>>> f &gt; e
False
>>> e
Set(['a', 0, 2, 3, 4, 1, ImmutableSet(['p'])])
>>> e.copy()
Set(['a', 0, 2, 3, 4, 1, ImmutableSet(['p'])])
>>> e.remove(3)
>>> e
Set(['a', 0, 2, 4, 1, ImmutableSet(['p'])])
>>> 0 in e
True
>>> e.pop()
'a'
>>> e
Set([0, 2, 4, 1, ImmutableSet(['p'])])
>>> e.pop()
0
>>> e.discard(4)
>>> e
Set([2, 1, ImmutableSet(['p'])])
>>> e.discard("p")
>>> e
Set([2, 1, ImmutableSet(['p'])])
>>> e.discard(sets.Set("p"))
>>> e
Set([2, 1])
>>>
>>> e -= f
>>> e
Set([])
>>> f
Set(['a', 2, 3, 4, 1])
>>>
>>> e.clear()
>>> e
Set([])
>>>
# copy
>>> h == e
False
>>> h != e
True
>>> u = h.copy()
>>> u
Set(['a', 'b', 't', 'o'])
Opérations ensemblistes
::
#Pas d'opération "+" :
>>> h = e + f
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'Set' and 'Set'
#La réunion :
>>> g = e or f
>>> g
Set(['t', 'o'])
autre notation :
>>> h | e
Set(['a', 'b', 't', 'o'])
>>> h & e
Set(['t', 'o'])
>>>
Le complémentaire :
>>> h = e ^ f
>>> h
Set(['a', 'b', 't', 'o'])
La différence :
>>> i = h - e
>>> i
L'intersection, la réunion, le complémentaire :
>>> f
Set(['a', 2, 3, 4, 1])
>>> f & e
Set(['a', 1, 2, 3, 4])
>>> f | e
Set(['a', 1, 2, 3, 4, 0])
>>> f ^ e
Set([0])
différence entre type et isinstance
------------------------------------
`type()` ne gère pas l'héritage alors que `isinstance()` si:
>>> class MyClass(object):
def __init__(self):
pass
>>> a = MyClass()
>>> type(a) == MyClass
True
>>> type(a) == object
False
>>> isinstance(a, MyClass)
True
>>> isinstance(a, object)
True
>>>
Dans la **PEP 8**, Guido demande explicitement d'utiliser isinstance et non type
.. note::
citation :
Object type comparisons should always use isinstance() instead
of comparing types directly.
Yes: if isinstance(obj, int):
No: if type(obj) is int:
inférence de type
~~~~~~~~~~~~~~~~~~~~~~
.. todo:: coercion, typage dynamique, inférence de type
exemple::
def addition_forte(x, y):
return int(x) + int(y)
def addition_faible(x, y):
return x + y
dans `addition_faible`, il n'y a pas de casting de type, on n'essaye pas
de transformer ça en un type donné, c'est-à-dire que si `x` et `y` sont
compatible, ça marche. Le typage est fort, on demande des types
>>> addition_faible("1", 4)
TypeError: cannot concatenate 'str' and 'int' objects
>>> addition_forte("1", 4)
TypeError: cannot concatenate 'str' and 'int' objects
>>> addition_faible("a", "b")
5
Remarquons que `addition_faible` renvoie forcément un type `int` tandis
que `addition_forte` peut renvoyer un autre type, ceci est dû au
polymorphisme paramétrique.
.. todo:: en python un type et une classe, c'est la même chose
.. todo:: "duck typing" en python
- le typage
- typage fort
- statique : déclaration ou bien inférence (déduction) lisible dans le source
(exemple : java)
- typage dynamique : une variable est typée en fonction de son contenu
- typage faible :
- une donnée n'aura pas spécialement de type : les nombres, les chaînes de
caractères, les booléens, etc. seront tous des scalaires et ne seront
différenciés que par leur valeur et par le contexte de leur utilisation

Binary file not shown.

After

Width:  |  Height:  |  Size: 673 B

View File

@ -0,0 +1,648 @@
/*
* basic.css
* ~~~~~~~~~
*
* Sphinx stylesheet -- basic theme.
*
* :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
/* -- main layout ----------------------------------------------------------- */
div.clearer {
clear: both;
}
/* -- relbar ---------------------------------------------------------------- */
div.related {
width: 100%;
font-size: 90%;
}
div.related h3 {
display: none;
}
div.related ul {
margin: 0;
padding: 0 0 0 10px;
list-style: none;
}
div.related li {
display: inline;
}
div.related li.right {
float: right;
margin-right: 5px;
}
/* -- sidebar --------------------------------------------------------------- */
div.sphinxsidebarwrapper {
padding: 10px 5px 0 10px;
}
div.sphinxsidebar {
float: left;
width: 230px;
margin-left: -100%;
font-size: 90%;
word-wrap: break-word;
overflow-wrap : break-word;
}
div.sphinxsidebar ul {
list-style: none;
}
div.sphinxsidebar ul ul,
div.sphinxsidebar ul.want-points {
margin-left: 20px;
list-style: square;
}
div.sphinxsidebar ul ul {
margin-top: 0;
margin-bottom: 0;
}
div.sphinxsidebar form {
margin-top: 10px;
}
div.sphinxsidebar input {
border: 1px solid #98dbcc;
font-family: sans-serif;
font-size: 1em;
}
div.sphinxsidebar #searchbox input[type="text"] {
width: 170px;
}
img {
border: 0;
max-width: 100%;
}
/* -- search page ----------------------------------------------------------- */
ul.search {
margin: 10px 0 0 20px;
padding: 0;
}
ul.search li {
padding: 5px 0 5px 20px;
background-image: url(file.png);
background-repeat: no-repeat;
background-position: 0 7px;
}
ul.search li a {
font-weight: bold;
}
ul.search li div.context {
color: #888;
margin: 2px 0 0 30px;
text-align: left;
}
ul.keywordmatches li.goodmatch a {
font-weight: bold;
}
/* -- index page ------------------------------------------------------------ */
table.contentstable {
width: 90%;
margin-left: auto;
margin-right: auto;
}
table.contentstable p.biglink {
line-height: 150%;
}
a.biglink {
font-size: 1.3em;
}
span.linkdescr {
font-style: italic;
padding-top: 5px;
font-size: 90%;
}
/* -- general index --------------------------------------------------------- */
table.indextable {
width: 100%;
}
table.indextable td {
text-align: left;
vertical-align: top;
}
table.indextable ul {
margin-top: 0;
margin-bottom: 0;
list-style-type: none;
}
table.indextable > tbody > tr > td > ul {
padding-left: 0em;
}
table.indextable tr.pcap {
height: 10px;
}
table.indextable tr.cap {
margin-top: 10px;
background-color: #f2f2f2;
}
img.toggler {
margin-right: 3px;
margin-top: 3px;
cursor: pointer;
}
div.modindex-jumpbox {
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
margin: 1em 0 1em 0;
padding: 0.4em;
}
div.genindex-jumpbox {
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
margin: 1em 0 1em 0;
padding: 0.4em;
}
/* -- domain module index --------------------------------------------------- */
table.modindextable td {
padding: 2px;
border-collapse: collapse;
}
/* -- general body styles --------------------------------------------------- */
div.body p, div.body dd, div.body li, div.body blockquote {
-moz-hyphens: auto;
-ms-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
a.headerlink {
visibility: hidden;
}
h1:hover > a.headerlink,
h2:hover > a.headerlink,
h3:hover > a.headerlink,
h4:hover > a.headerlink,
h5:hover > a.headerlink,
h6:hover > a.headerlink,
dt:hover > a.headerlink,
caption:hover > a.headerlink,
p.caption:hover > a.headerlink,
div.code-block-caption:hover > a.headerlink {
visibility: visible;
}
div.body p.caption {
text-align: inherit;
}
div.body td {
text-align: left;
}
.first {
margin-top: 0 !important;
}
p.rubric {
margin-top: 30px;
font-weight: bold;
}
img.align-left, .figure.align-left, object.align-left {
clear: left;
float: left;
margin-right: 1em;
}
img.align-right, .figure.align-right, object.align-right {
clear: right;
float: right;
margin-left: 1em;
}
img.align-center, .figure.align-center, object.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
.align-left {
text-align: left;
}
.align-center {
text-align: center;
}
.align-right {
text-align: right;
}
/* -- sidebars -------------------------------------------------------------- */
div.sidebar {
margin: 0 0 0.5em 1em;
border: 1px solid #ddb;
padding: 7px 7px 0 7px;
background-color: #ffe;
width: 40%;
float: right;
}
p.sidebar-title {
font-weight: bold;
}
/* -- topics ---------------------------------------------------------------- */
div.topic {
border: 1px solid #ccc;
padding: 7px 7px 0 7px;
margin: 10px 0 10px 0;
}
p.topic-title {
font-size: 1.1em;
font-weight: bold;
margin-top: 10px;
}
/* -- admonitions ----------------------------------------------------------- */
div.admonition {
margin-top: 10px;
margin-bottom: 10px;
padding: 7px;
}
div.admonition dt {
font-weight: bold;
}
div.admonition dl {
margin-bottom: 0;
}
p.admonition-title {
margin: 0px 10px 5px 0px;
font-weight: bold;
}
div.body p.centered {
text-align: center;
margin-top: 25px;
}
/* -- tables ---------------------------------------------------------------- */
table.docutils {
border: 0;
border-collapse: collapse;
}
table.align-center {
margin-left: auto;
margin-right: auto;
}
table caption span.caption-number {
font-style: italic;
}
table caption span.caption-text {
}
table.docutils td, table.docutils th {
padding: 1px 8px 1px 5px;
border-top: 0;
border-left: 0;
border-right: 0;
border-bottom: 1px solid #aaa;
}
table.footnote td, table.footnote th {
border: 0 !important;
}
th {
text-align: left;
padding-right: 5px;
}
table.citation {
border-left: solid 1px gray;
margin-left: 1px;
}
table.citation td {
border-bottom: none;
}
/* -- figures --------------------------------------------------------------- */
div.figure {
margin: 0.5em;
padding: 0.5em;
}
div.figure p.caption {
padding: 0.3em;
}
div.figure p.caption span.caption-number {
font-style: italic;
}
div.figure p.caption span.caption-text {
}
/* -- field list styles ----------------------------------------------------- */
table.field-list td, table.field-list th {
border: 0 !important;
}
.field-list ul {
margin: 0;
padding-left: 1em;
}
.field-list p {
margin: 0;
}
.field-name {
-moz-hyphens: manual;
-ms-hyphens: manual;
-webkit-hyphens: manual;
hyphens: manual;
}
/* -- other body styles ----------------------------------------------------- */
ol.arabic {
list-style: decimal;
}
ol.loweralpha {
list-style: lower-alpha;
}
ol.upperalpha {
list-style: upper-alpha;
}
ol.lowerroman {
list-style: lower-roman;
}
ol.upperroman {
list-style: upper-roman;
}
dl {
margin-bottom: 15px;
}
dd p {
margin-top: 0px;
}
dd ul, dd table {
margin-bottom: 10px;
}
dd {
margin-top: 3px;
margin-bottom: 10px;
margin-left: 30px;
}
dt:target, span.highlighted {
background-color: #fbe54e;
}
rect.highlighted {
fill: #fbe54e;
}
dl.glossary dt {
font-weight: bold;
font-size: 1.1em;
}
.optional {
font-size: 1.3em;
}
.sig-paren {
font-size: larger;
}
.versionmodified {
font-style: italic;
}
.system-message {
background-color: #fda;
padding: 5px;
border: 3px solid red;
}
.footnote:target {
background-color: #ffa;
}
.line-block {
display: block;
margin-top: 1em;
margin-bottom: 1em;
}
.line-block .line-block {
margin-top: 0;
margin-bottom: 0;
margin-left: 1.5em;
}
.guilabel, .menuselection {
font-family: sans-serif;
}
.accelerator {
text-decoration: underline;
}
.classifier {
font-style: oblique;
}
abbr, acronym {
border-bottom: dotted 1px;
cursor: help;
}
/* -- code displays --------------------------------------------------------- */
pre {
overflow: auto;
overflow-y: hidden; /* fixes display issues on Chrome browsers */
}
span.pre {
-moz-hyphens: none;
-ms-hyphens: none;
-webkit-hyphens: none;
hyphens: none;
}
td.linenos pre {
padding: 5px 0px;
border: 0;
background-color: transparent;
color: #aaa;
}
table.highlighttable {
margin-left: 0.5em;
}
table.highlighttable td {
padding: 0 0.5em 0 0.5em;
}
div.code-block-caption {
padding: 2px 5px;
font-size: small;
}
div.code-block-caption code {
background-color: transparent;
}
div.code-block-caption + div > div.highlight > pre {
margin-top: 0;
}
div.code-block-caption span.caption-number {
padding: 0.1em 0.3em;
font-style: italic;
}
div.code-block-caption span.caption-text {
}
div.literal-block-wrapper {
padding: 1em 1em 0;
}
div.literal-block-wrapper div.highlight {
margin: 0;
}
code.descname {
background-color: transparent;
font-weight: bold;
font-size: 1.2em;
}
code.descclassname {
background-color: transparent;
}
code.xref, a code {
background-color: transparent;
font-weight: bold;
}
h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
background-color: transparent;
}
.viewcode-link {
float: right;
}
.viewcode-back {
float: right;
font-family: sans-serif;
}
div.viewcode-block:target {
margin: -1px -10px;
padding: 0 10px;
}
/* -- math display ---------------------------------------------------------- */
img.math {
vertical-align: middle;
}
div.body div.math p {
text-align: center;
}
span.eqno {
float: right;
}
span.eqno a.headerlink {
position: relative;
left: 0px;
z-index: 1;
}
div.math:hover a.headerlink {
visibility: visible;
}
/* -- printout stylesheet --------------------------------------------------- */
@media print {
div.document,
div.documentwrapper,
div.bodywrapper {
margin: 0 !important;
width: 100%;
}
div.sphinxsidebar,
div.related,
div.footer,
#top-link {
display: none;
}
}

View File

@ -0,0 +1,261 @@
/*
* classic.css_t
* ~~~~~~~~~~~~~
*
* Sphinx stylesheet -- classic theme.
*
* :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
@import url("basic.css");
/* -- page layout ----------------------------------------------------------- */
body {
font-family: sans-serif;
font-size: 100%;
background-color: #11303d;
color: #000;
margin: 0;
padding: 0;
}
div.document {
background-color: #1c4e63;
}
div.documentwrapper {
float: left;
width: 100%;
}
div.bodywrapper {
margin: 0 0 0 230px;
}
div.body {
background-color: #ffffff;
color: #000000;
padding: 0 20px 30px 20px;
}
div.footer {
color: #ffffff;
width: 100%;
padding: 9px 0 9px 0;
text-align: center;
font-size: 75%;
}
div.footer a {
color: #ffffff;
text-decoration: underline;
}
div.related {
background-color: #133f52;
line-height: 30px;
color: #ffffff;
}
div.related a {
color: #ffffff;
}
div.sphinxsidebar {
}
div.sphinxsidebar h3 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.4em;
font-weight: normal;
margin: 0;
padding: 0;
}
div.sphinxsidebar h3 a {
color: #ffffff;
}
div.sphinxsidebar h4 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.3em;
font-weight: normal;
margin: 5px 0 0 0;
padding: 0;
}
div.sphinxsidebar p {
color: #ffffff;
}
div.sphinxsidebar p.topless {
margin: 5px 10px 10px 10px;
}
div.sphinxsidebar ul {
margin: 10px;
padding: 0;
color: #ffffff;
}
div.sphinxsidebar a {
color: #98dbcc;
}
div.sphinxsidebar input {
border: 1px solid #98dbcc;
font-family: sans-serif;
font-size: 1em;
}
/* -- hyperlink styles ------------------------------------------------------ */
a {
color: #355f7c;
text-decoration: none;
}
a:visited {
color: #355f7c;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* -- body styles ----------------------------------------------------------- */
div.body h1,
div.body h2,
div.body h3,
div.body h4,
div.body h5,
div.body h6 {
font-family: 'Trebuchet MS', sans-serif;
background-color: #f2f2f2;
font-weight: normal;
color: #20435c;
border-bottom: 1px solid #ccc;
margin: 20px -20px 10px -20px;
padding: 3px 0 3px 10px;
}
div.body h1 { margin-top: 0; font-size: 200%; }
div.body h2 { font-size: 160%; }
div.body h3 { font-size: 140%; }
div.body h4 { font-size: 120%; }
div.body h5 { font-size: 110%; }
div.body h6 { font-size: 100%; }
a.headerlink {
color: #c60f0f;
font-size: 0.8em;
padding: 0 4px 0 4px;
text-decoration: none;
}
a.headerlink:hover {
background-color: #c60f0f;
color: white;
}
div.body p, div.body dd, div.body li, div.body blockquote {
text-align: justify;
line-height: 130%;
}
div.admonition p.admonition-title + p {
display: inline;
}
div.admonition p {
margin-bottom: 5px;
}
div.admonition pre {
margin-bottom: 5px;
}
div.admonition ul, div.admonition ol {
margin-bottom: 5px;
}
div.note {
background-color: #eee;
border: 1px solid #ccc;
}
div.seealso {
background-color: #ffc;
border: 1px solid #ff6;
}
div.topic {
background-color: #eee;
}
div.warning {
background-color: #ffe4e4;
border: 1px solid #f66;
}
p.admonition-title {
display: inline;
}
p.admonition-title:after {
content: ":";
}
pre {
padding: 5px;
background-color: #eeffcc;
color: #333333;
line-height: 120%;
border: 1px solid #ac9;
border-left: none;
border-right: none;
}
code {
background-color: #ecf0f3;
padding: 0 1px 0 1px;
font-size: 0.95em;
}
th {
background-color: #ede;
}
.warning code {
background: #efc2c2;
}
.note code {
background: #d6d6d6;
}
.viewcode-back {
font-family: sans-serif;
}
div.viewcode-block:target {
background-color: #f4debf;
border-top: 1px solid #ac9;
border-bottom: 1px solid #ac9;
}
div.code-block-caption {
color: #efefef;
background-color: #1c4e63;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 756 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 829 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 641 B

View File

@ -0,0 +1,849 @@
/**
* Sphinx Doc Design
*/
body {
font-family: sans-serif;
font-size: 100%;
/* background-color: #11303d; */
background-color: #222;
color: #000;
margin: 0;
padding: 0;
}
/* :::: LAYOUT :::: */
div.document {
background-color: #000000 ; /* #1c4e63; */
}
div.documentwrapper {
float: left;
width: 100%;
}
div.bodywrapper {
margin: 0 0 0 230px;
}
div.body {
background-color: white;
padding: 0 20px 30px 20px;
}
div.sphinxsidebarwrapper {
padding: 10px 5px 0 10px;
}
div.sphinxsidebar {
float: left;
width: 230px;
margin-left: -100%;
font-size: 90%;
}
div.clearer {
clear: both;
}
div.footer {
color: #fff;
width: 100%;
padding: 9px 0 9px 0;
text-align: center;
font-size: 75%;
}
div.footer a {
color: #fff;
text-decoration: underline;
}
div.related {
background-color: #133f52;
color: #fff;
width: 100%;
line-height: 30px;
font-size: 90%;
}
div.related h3 {
display: none;
}
div.related ul {
margin: 0;
padding: 0 0 0 10px;
list-style: none;
}
div.related li {
display: inline;
}
div.related li.right {
float: right;
margin-right: 5px;
}
div.related a {
color: white;
}
/* ::: TOC :::: */
div.sphinxsidebar h3 {
font-family: 'Trebuchet MS', sans-serif;
color: white;
font-size: 1.4em;
font-weight: normal;
margin: 0;
padding: 0;
}
div.sphinxsidebar h3 a {
color: white;
}
div.sphinxsidebar h4 {
font-family: 'Trebuchet MS', sans-serif;
color: white;
font-size: 1.3em;
font-weight: normal;
margin: 5px 0 0 0;
padding: 0;
}
div.sphinxsidebar p {
color: white;
}
div.sphinxsidebar p.topless {
margin: 5px 10px 10px 10px;
}
div.sphinxsidebar ul {
margin: 10px;
padding: 0;
list-style: none;
color: white;
}
div.sphinxsidebar ul ul,
div.sphinxsidebar ul.want-points {
margin-left: 20px;
list-style: square;
}
div.sphinxsidebar ul ul {
margin-top: 0;
margin-bottom: 0;
}
div.sphinxsidebar a {
color: #98dbcc;
}
div.sphinxsidebar form {
margin-top: 10px;
}
div.sphinxsidebar input {
border: 1px solid #98dbcc;
font-family: sans-serif;
font-size: 1em;
}
/* :::: MODULE CLOUD :::: */
div.modulecloud {
margin: -5px 10px 5px 10px;
padding: 10px;
line-height: 160%;
border: 1px solid #cbe7e5;
background-color: #f2fbfd;
}
div.modulecloud a {
padding: 0 5px 0 5px;
}
/* :::: SEARCH :::: */
ul.search {
margin: 10px 0 0 20px;
padding: 0;
}
ul.search li {
padding: 5px 0 5px 20px;
background-image: url(file.png);
background-repeat: no-repeat;
background-position: 0 7px;
}
ul.search li a {
font-weight: bold;
}
ul.search li div.context {
color: #888;
margin: 2px 0 0 30px;
text-align: left;
}
ul.keywordmatches li.goodmatch a {
font-weight: bold;
}
/* :::: COMMON FORM STYLES :::: */
div.actions {
padding: 5px 10px 5px 10px;
border-top: 1px solid #cbe7e5;
border-bottom: 1px solid #cbe7e5;
background-color: #e0f6f4;
}
form dl {
color: #333;
}
form dt {
clear: both;
float: left;
min-width: 110px;
margin-right: 10px;
padding-top: 2px;
}
input#homepage {
display: none;
}
div.error {
margin: 5px 20px 0 0;
padding: 5px;
border: 1px solid #d00;
font-weight: bold;
}
/* :::: INLINE COMMENTS :::: */
div.inlinecomments {
position: absolute;
right: 20px;
}
div.inlinecomments a.bubble {
display: block;
float: right;
background-image: url(style/comment.png);
background-repeat: no-repeat;
width: 25px;
height: 25px;
text-align: center;
padding-top: 3px;
font-size: 0.9em;
line-height: 14px;
font-weight: bold;
color: black;
}
div.inlinecomments a.bubble span {
display: none;
}
div.inlinecomments a.emptybubble {
background-image: url(style/nocomment.png);
}
div.inlinecomments a.bubble:hover {
background-image: url(style/hovercomment.png);
text-decoration: none;
color: #3ca0a4;
}
div.inlinecomments div.comments {
float: right;
margin: 25px 5px 0 0;
max-width: 50em;
min-width: 30em;
border: 1px solid #2eabb0;
background-color: #f2fbfd;
z-index: 150;
}
div#comments {
border: 1px solid #2eabb0;
margin-top: 20px;
}
div#comments div.nocomments {
padding: 10px;
font-weight: bold;
}
div.inlinecomments div.comments h3,
div#comments h3 {
margin: 0;
padding: 0;
background-color: #2eabb0;
color: white;
border: none;
padding: 3px;
}
div.inlinecomments div.comments div.actions {
padding: 4px;
margin: 0;
border-top: none;
}
div#comments div.comment {
margin: 10px;
border: 1px solid #2eabb0;
}
div.inlinecomments div.comment h4,
div.commentwindow div.comment h4,
div#comments div.comment h4 {
margin: 10px 0 0 0;
background-color: #2eabb0;
color: white;
border: none;
padding: 1px 4px 1px 4px;
}
div#comments div.comment h4 {
margin: 0;
}
div#comments div.comment h4 a {
color: #d5f4f4;
}
div.inlinecomments div.comment div.text,
div.commentwindow div.comment div.text,
div#comments div.comment div.text {
margin: -5px 0 -5px 0;
padding: 0 10px 0 10px;
}
div.inlinecomments div.comment div.meta,
div.commentwindow div.comment div.meta,
div#comments div.comment div.meta {
text-align: right;
padding: 2px 10px 2px 0;
font-size: 95%;
color: #538893;
border-top: 1px solid #cbe7e5;
background-color: #e0f6f4;
}
div.commentwindow {
position: absolute;
width: 500px;
border: 1px solid #cbe7e5;
background-color: #f2fbfd;
display: none;
z-index: 130;
}
div.commentwindow h3 {
margin: 0;
background-color: #2eabb0;
color: white;
border: none;
padding: 5px;
font-size: 1.5em;
cursor: pointer;
}
div.commentwindow div.actions {
margin: 10px -10px 0 -10px;
padding: 4px 10px 4px 10px;
color: #538893;
}
div.commentwindow div.actions input {
border: 1px solid #2eabb0;
background-color: white;
color: #135355;
cursor: pointer;
}
div.commentwindow div.form {
padding: 0 10px 0 10px;
}
div.commentwindow div.form input,
div.commentwindow div.form textarea {
border: 1px solid #3c9ea2;
background-color: white;
color: black;
}
div.commentwindow div.error {
margin: 10px 5px 10px 5px;
background-color: #fbe5dc;
display: none;
}
div.commentwindow div.form textarea {
width: 99%;
}
div.commentwindow div.preview {
margin: 10px 0 10px 0;
background-color: #70d0d4;
padding: 0 1px 1px 25px;
}
div.commentwindow div.preview h4 {
margin: 0 0 -5px -20px;
padding: 4px 0 0 4px;
color: white;
font-size: 1.3em;
}
div.commentwindow div.preview div.comment {
background-color: #f2fbfd;
}
div.commentwindow div.preview div.comment h4 {
margin: 10px 0 0 0!important;
padding: 1px 4px 1px 4px!important;
font-size: 1.2em;
}
/* :::: SUGGEST CHANGES :::: */
div#suggest-changes-box input, div#suggest-changes-box textarea {
border: 1px solid #ccc;
background-color: white;
color: black;
}
div#suggest-changes-box textarea {
width: 99%;
height: 400px;
}
/* :::: PREVIEW :::: */
div.preview {
background-image: url(style/preview.png);
padding: 0 20px 20px 20px;
margin-bottom: 30px;
}
/* :::: INDEX PAGE :::: */
table.contentstable {
width: 90%;
}
table.contentstable p.biglink {
line-height: 150%;
}
a.biglink {
font-size: 1.3em;
}
span.linkdescr {
font-style: italic;
padding-top: 5px;
font-size: 90%;
}
/* :::: INDEX STYLES :::: */
table.indextable td {
text-align: left;
vertical-align: top;
}
table.indextable dl, table.indextable dd {
margin-top: 0;
margin-bottom: 0;
}
table.indextable tr.pcap {
height: 10px;
}
table.indextable tr.cap {
margin-top: 10px;
background-color: #f2f2f2;
}
img.toggler {
margin-right: 3px;
margin-top: 3px;
cursor: pointer;
}
form.pfform {
margin: 10px 0 20px 0;
}
/* :::: GLOBAL STYLES :::: */
.docwarning {
background-color: #ffe4e4;
padding: 10px;
margin: 0 -20px 0 -20px;
border-bottom: 1px solid #f66;
}
p.subhead {
font-weight: bold;
margin-top: 20px;
}
a {
color: #355f7c;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
div.body h1,
div.body h2,
div.body h3,
div.body h4,
div.body h5,
div.body h6 {
font-family: 'Trebuchet MS', sans-serif;
background-color: #f2f2f2;
font-weight: normal;
color: #20435c;
border-bottom: 1px solid #ccc;
margin: 20px -20px 10px -20px;
padding: 3px 0 3px 10px;
}
div.body h1 { margin-top: 0; font-size: 200%; }
div.body h2 { font-size: 160%; }
div.body h3 { font-size: 140%; }
div.body h4 { font-size: 120%; }
div.body h5 { font-size: 110%; }
div.body h6 { font-size: 100%; }
a.headerlink {
color: #c60f0f;
font-size: 0.8em;
padding: 0 4px 0 4px;
text-decoration: none;
visibility: hidden;
}
h1:hover > a.headerlink,
h2:hover > a.headerlink,
h3:hover > a.headerlink,
h4:hover > a.headerlink,
h5:hover > a.headerlink,
h6:hover > a.headerlink,
dt:hover > a.headerlink {
visibility: visible;
}
a.headerlink:hover {
background-color: #c60f0f;
color: white;
}
div.body p, div.body dd, div.body li {
text-align: justify;
line-height: 130%;
}
div.body p.caption {
text-align: inherit;
}
div.body td {
text-align: left;
}
ul.fakelist {
list-style: none;
margin: 10px 0 10px 20px;
padding: 0;
}
.field-list ul {
padding-left: 1em;
}
.first {
margin-top: 0 !important;
}
/* "Footnotes" heading */
p.rubric {
margin-top: 30px;
font-weight: bold;
}
/* "Topics" */
div.topic {
background-color: #eee;
border: 1px solid #ccc;
padding: 0 7px 0 7px;
margin: 10px 0 10px 0;
}
p.topic-title {
font-size: 1.1em;
font-weight: bold;
margin-top: 10px;
}
/* Admonitions */
div.admonition {
margin-top: 10px;
margin-bottom: 10px;
padding: 7px;
}
div.admonition dt {
font-weight: bold;
}
div.admonition dl {
margin-bottom: 0;
}
div.admonition p {
display: inline;
}
div.seealso {
background-color: #ffc;
border: 1px solid #ff6;
}
div.warning {
background-color: #ffe4e4;
border: 1px solid #f66;
}
div.note {
background-color: #eee;
border: 1px solid #ccc;
}
p.admonition-title {
margin: 0px 10px 5px 0px;
font-weight: bold;
display: inline;
}
p.admonition-title:after {
content: ":";
}
div.body p.centered {
text-align: center;
margin-top: 25px;
}
table.docutils {
border: 0;
}
table.docutils td, table.docutils th {
padding: 1px 8px 1px 0;
border-top: 0;
border-left: 0;
border-right: 0;
border-bottom: 1px solid #aaa;
}
table.field-list td, table.field-list th {
border: 0 !important;
}
table.footnote td, table.footnote th {
border: 0 !important;
}
.field-list ul {
margin: 0;
padding-left: 1em;
}
.field-list p {
margin: 0;
}
dl {
margin-bottom: 15px;
clear: both;
}
dd p {
margin-top: 0px;
}
dd ul, dd table {
margin-bottom: 10px;
}
dd {
margin-top: 3px;
margin-bottom: 10px;
margin-left: 30px;
}
.refcount {
color: #060;
}
dt:target,
.highlight {
background-color: #fbe54e;
}
dl.glossary dt {
font-weight: bold;
font-size: 1.1em;
}
th {
text-align: left;
padding-right: 5px;
}
pre {
padding: 5px;
background-color: #efc;
color: #333;
border: 1px solid #ac9;
border-left: none;
border-right: none;
overflow: auto;
}
td.linenos pre {
padding: 5px 0px;
border: 0;
background-color: transparent;
color: #aaa;
}
table.highlighttable {
margin-left: 0.5em;
}
table.highlighttable td {
padding: 0 0.5em 0 0.5em;
}
tt {
background-color: #ecf0f3;
padding: 0 1px 0 1px;
font-size: 0.95em;
}
tt.descname {
background-color: transparent;
font-weight: bold;
font-size: 1.2em;
}
tt.descclassname {
background-color: transparent;
}
tt.xref, a tt {
background-color: transparent;
font-weight: bold;
}
.footnote:target { background-color: #ffa }
h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
background-color: transparent;
}
.optional {
font-size: 1.3em;
}
.versionmodified {
font-style: italic;
}
form.comment {
margin: 0;
padding: 10px 30px 10px 30px;
background-color: #eee;
}
form.comment h3 {
background-color: #326591;
color: white;
margin: -10px -30px 10px -30px;
padding: 5px;
font-size: 1.4em;
}
form.comment input,
form.comment textarea {
border: 1px solid #ccc;
padding: 2px;
font-family: sans-serif;
font-size: 100%;
}
form.comment input[type="text"] {
width: 240px;
}
form.comment textarea {
width: 100%;
height: 200px;
margin-bottom: 10px;
}
.system-message {
background-color: #fda;
padding: 5px;
border: 3px solid red;
}
div.math {
text-align: center;
}
span.eqno {
float: right;
}
img.logo {
border: 0;
}
/* :::: PRINT :::: */
@media print {
div.document,
div.documentwrapper,
div.bodywrapper {
margin: 0;
width : 100%;
}
div.sphinxsidebar,
div.related,
div.footer,
div#comments div.new-comment-box,
#top-link {
display: none;
}
}

View File

@ -0,0 +1,311 @@
/*
* doctools.js
* ~~~~~~~~~~~
*
* Sphinx JavaScript utilities for all documentation.
*
* :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
/**
* select a different prefix for underscore
*/
$u = _.noConflict();
/**
* make the code below compatible with browsers without
* an installed firebug like debugger
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
"dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
"profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {};
}
*/
/**
* small helper function to urldecode strings
*/
jQuery.urldecode = function(x) {
return decodeURIComponent(x).replace(/\+/g, ' ');
};
/**
* small helper function to urlencode strings
*/
jQuery.urlencode = encodeURIComponent;
/**
* This function returns the parsed url parameters of the
* current request. Multiple values per key are supported,
* it will always return arrays of strings for the value parts.
*/
jQuery.getQueryParameters = function(s) {
if (typeof s === 'undefined')
s = document.location.search;
var parts = s.substr(s.indexOf('?') + 1).split('&');
var result = {};
for (var i = 0; i < parts.length; i++) {
var tmp = parts[i].split('=', 2);
var key = jQuery.urldecode(tmp[0]);
var value = jQuery.urldecode(tmp[1]);
if (key in result)
result[key].push(value);
else
result[key] = [value];
}
return result;
};
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node, addItems) {
if (node.nodeType === 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {
var span;
var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg");
if (isInSVG) {
span = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
} else {
span = document.createElement("span");
span.className = className;
}
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
if (isInSVG) {
var bbox = span.getBBox();
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.x.baseVal.value = bbox.x;
rect.y.baseVal.value = bbox.y;
rect.width.baseVal.value = bbox.width;
rect.height.baseVal.value = bbox.height;
rect.setAttribute('class', className);
var parentOfText = node.parentNode.parentNode;
addItems.push({
"parent": node.parentNode,
"target": rect});
}
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this, addItems);
});
}
}
var addItems = [];
var result = this.each(function() {
highlight(this, addItems);
});
for (var i = 0; i < addItems.length; ++i) {
jQuery(addItems[i].parent).before(addItems[i].target);
}
return result;
};
/*
* backward compatibility for jQuery.browser
* This will be supported until firefox bug is fixed.
*/
if (!jQuery.browser) {
jQuery.uaMatch = function(ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
/(webkit)[ \/]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
jQuery.browser = {};
jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
}
/**
* Small JavaScript module for the documentation.
*/
var Documentation = {
init : function() {
this.fixFirefoxAnchorBug();
this.highlightSearchWords();
this.initIndexTable();
},
/**
* i18n support
*/
TRANSLATIONS : {},
PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; },
LOCALE : 'unknown',
// gettext and ngettext don't access this so that the functions
// can safely bound to a different name (_ = Documentation.gettext)
gettext : function(string) {
var translated = Documentation.TRANSLATIONS[string];
if (typeof translated === 'undefined')
return string;
return (typeof translated === 'string') ? translated : translated[0];
},
ngettext : function(singular, plural, n) {
var translated = Documentation.TRANSLATIONS[singular];
if (typeof translated === 'undefined')
return (n == 1) ? singular : plural;
return translated[Documentation.PLURALEXPR(n)];
},
addTranslations : function(catalog) {
for (var key in catalog.messages)
this.TRANSLATIONS[key] = catalog.messages[key];
this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
this.LOCALE = catalog.locale;
},
/**
* add context elements like header anchor links
*/
addContextElements : function() {
$('div[id] > :header:first').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this headline')).
appendTo(this);
});
$('dt[id]').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this definition')).
appendTo(this);
});
},
/**
* workaround a firefox stupidity
* see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
*/
fixFirefoxAnchorBug : function() {
if (document.location.hash && $.browser.mozilla)
window.setTimeout(function() {
document.location.href += '';
}, 10);
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
if (!body.length) {
body = $('body');
}
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlighted');
});
}, 10);
$('<p class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
.appendTo($('#searchbox'));
}
},
/**
* init the domain index toggle buttons
*/
initIndexTable : function() {
var togglers = $('img.toggler').click(function() {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
$('tr.cg-' + idnum).toggle();
if (src.substr(-9) === 'minus.png')
$(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
else
$(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
togglers.click();
}
},
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('#searchbox .highlight-link').fadeOut(300);
$('span.highlighted').removeClass('highlighted');
},
/**
* make the url absolute
*/
makeURL : function(relativeURL) {
return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
},
/**
* get the current relative url
*/
getCurrentURL : function() {
var path = document.location.pathname;
var parts = path.split(/\//);
$.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
if (this === '..')
parts.pop();
});
var url = parts.join('/');
return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
},
initOnKeyListeners: function() {
$(document).keyup(function(event) {
var activeElementType = document.activeElement.tagName;
// don't navigate when in search box or textarea
if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') {
switch (event.keyCode) {
case 37: // left
var prevHref = $('link[rel="prev"]').prop('href');
if (prevHref) {
window.location.href = prevHref;
return false;
}
case 39: // right
var nextHref = $('link[rel="next"]').prop('href');
if (nextHref) {
window.location.href = nextHref;
return false;
}
}
}
});
}
};
// quick alias for translations
_ = Documentation.gettext;
$(document).ready(function() {
Documentation.init();
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 B

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 B

View File

@ -0,0 +1,5 @@
div.header, div.relnav, #toc { display: none; }
#contentwrapper { padding: 0; margin: 0; border: none; }
body { color: black; background-color: white; }
div.footer { border-top: 1px solid #888; color: #888; margin-top: 1cm; }
div.footer a { text-decoration: none; }

View File

@ -0,0 +1,69 @@
.highlight .hll { background-color: #ffffcc }
.highlight { background: #eeffcc; }
.highlight .c { color: #408090; font-style: italic } /* Comment */
.highlight .err { border: 1px solid #FF0000 } /* Error */
.highlight .k { color: #007020; font-weight: bold } /* Keyword */
.highlight .o { color: #666666 } /* Operator */
.highlight .ch { color: #408090; font-style: italic } /* Comment.Hashbang */
.highlight .cm { color: #408090; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #007020 } /* Comment.Preproc */
.highlight .cpf { color: #408090; font-style: italic } /* Comment.PreprocFile */
.highlight .c1 { color: #408090; font-style: italic } /* Comment.Single */
.highlight .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #A00000 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #FF0000 } /* Generic.Error */
.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight .gi { color: #00A000 } /* Generic.Inserted */
.highlight .go { color: #333333 } /* Generic.Output */
.highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight .gt { color: #0044DD } /* Generic.Traceback */
.highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #007020 } /* Keyword.Pseudo */
.highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #902000 } /* Keyword.Type */
.highlight .m { color: #208050 } /* Literal.Number */
.highlight .s { color: #4070a0 } /* Literal.String */
.highlight .na { color: #4070a0 } /* Name.Attribute */
.highlight .nb { color: #007020 } /* Name.Builtin */
.highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */
.highlight .no { color: #60add5 } /* Name.Constant */
.highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */
.highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */
.highlight .ne { color: #007020 } /* Name.Exception */
.highlight .nf { color: #06287e } /* Name.Function */
.highlight .nl { color: #002070; font-weight: bold } /* Name.Label */
.highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
.highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #bb60d5 } /* Name.Variable */
.highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #208050 } /* Literal.Number.Bin */
.highlight .mf { color: #208050 } /* Literal.Number.Float */
.highlight .mh { color: #208050 } /* Literal.Number.Hex */
.highlight .mi { color: #208050 } /* Literal.Number.Integer */
.highlight .mo { color: #208050 } /* Literal.Number.Oct */
.highlight .sa { color: #4070a0 } /* Literal.String.Affix */
.highlight .sb { color: #4070a0 } /* Literal.String.Backtick */
.highlight .sc { color: #4070a0 } /* Literal.String.Char */
.highlight .dl { color: #4070a0 } /* Literal.String.Delimiter */
.highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */
.highlight .s2 { color: #4070a0 } /* Literal.String.Double */
.highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */
.highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */
.highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */
.highlight .sx { color: #c65d09 } /* Literal.String.Other */
.highlight .sr { color: #235388 } /* Literal.String.Regex */
.highlight .s1 { color: #4070a0 } /* Literal.String.Single */
.highlight .ss { color: #517918 } /* Literal.String.Symbol */
.highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #06287e } /* Name.Function.Magic */
.highlight .vc { color: #bb60d5 } /* Name.Variable.Class */
.highlight .vg { color: #bb60d5 } /* Name.Variable.Global */
.highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */
.highlight .vm { color: #bb60d5 } /* Name.Variable.Magic */
.highlight .il { color: #208050 } /* Literal.Number.Integer.Long */

View File

@ -0,0 +1,761 @@
/*
* searchtools.js_t
* ~~~~~~~~~~~~~~~~
*
* Sphinx JavaScript utilities for the full-text search.
*
* :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
/* Non-minified version JS is _stemmer.js if file is provided */
/**
* Porter Stemmer
*/
var Stemmer = function() {
var step2list = {
ational: 'ate',
tional: 'tion',
enci: 'ence',
anci: 'ance',
izer: 'ize',
bli: 'ble',
alli: 'al',
entli: 'ent',
eli: 'e',
ousli: 'ous',
ization: 'ize',
ation: 'ate',
ator: 'ate',
alism: 'al',
iveness: 'ive',
fulness: 'ful',
ousness: 'ous',
aliti: 'al',
iviti: 'ive',
biliti: 'ble',
logi: 'log'
};
var step3list = {
icate: 'ic',
ative: '',
alize: 'al',
iciti: 'ic',
ical: 'ic',
ful: '',
ness: ''
};
var c = "[^aeiou]"; // consonant
var v = "[aeiouy]"; // vowel
var C = c + "[^aeiouy]*"; // consonant sequence
var V = v + "[aeiou]*"; // vowel sequence
var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
var s_v = "^(" + C + ")?" + v; // vowel in stem
this.stemWord = function (w) {
var stem;
var suffix;
var firstch;
var origword = w;
if (w.length < 3)
return w;
var re;
var re2;
var re3;
var re4;
firstch = w.substr(0,1);
if (firstch == "y")
w = firstch.toUpperCase() + w.substr(1);
// Step 1a
re = /^(.+?)(ss|i)es$/;
re2 = /^(.+?)([^s])s$/;
if (re.test(w))
w = w.replace(re,"$1$2");
else if (re2.test(w))
w = w.replace(re2,"$1$2");
// Step 1b
re = /^(.+?)eed$/;
re2 = /^(.+?)(ed|ing)$/;
if (re.test(w)) {
var fp = re.exec(w);
re = new RegExp(mgr0);
if (re.test(fp[1])) {
re = /.$/;
w = w.replace(re,"");
}
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
re2 = new RegExp(s_v);
if (re2.test(stem)) {
w = stem;
re2 = /(at|bl|iz)$/;
re3 = new RegExp("([^aeiouylsz])\\1$");
re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re2.test(w))
w = w + "e";
else if (re3.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
else if (re4.test(w))
w = w + "e";
}
}
// Step 1c
re = /^(.+?)y$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(s_v);
if (re.test(stem))
w = stem + "i";
}
// Step 2
re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step2list[suffix];
}
// Step 3
re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step3list[suffix];
}
// Step 4
re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
re2 = /^(.+?)(s|t)(ion)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
if (re.test(stem))
w = stem;
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1] + fp[2];
re2 = new RegExp(mgr1);
if (re2.test(stem))
w = stem;
}
// Step 5
re = /^(.+?)e$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
re2 = new RegExp(meq1);
re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
w = stem;
}
re = /ll$/;
re2 = new RegExp(mgr1);
if (re.test(w) && re2.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
// and turn initial Y back to y
if (firstch == "y")
w = firstch.toLowerCase() + w.substr(1);
return w;
}
}
/**
* Simple result scoring code.
*/
var Scorer = {
// Implement the following function to further tweak the score for each result
// The function takes a result array [filename, title, anchor, descr, score]
// and returns the new score.
/*
score: function(result) {
return result[4];
},
*/
// query matches the full name of an object
objNameMatch: 11,
// or matches in the last dotted part of the object name
objPartialMatch: 6,
// Additive scores depending on the priority of the object
objPrio: {0: 15, // used to be importantResults
1: 5, // used to be objectResults
2: -5}, // used to be unimportantResults
// Used when the priority is not in the mapping.
objPrioDefault: 0,
// query found in title
title: 15,
// query found in terms
term: 5
};
var splitChars = (function() {
var result = {};
var singles = [96, 180, 187, 191, 215, 247, 749, 885, 903, 907, 909, 930, 1014, 1648,
1748, 1809, 2416, 2473, 2481, 2526, 2601, 2609, 2612, 2615, 2653, 2702,
2706, 2729, 2737, 2740, 2857, 2865, 2868, 2910, 2928, 2948, 2961, 2971,
2973, 3085, 3089, 3113, 3124, 3213, 3217, 3241, 3252, 3295, 3341, 3345,
3369, 3506, 3516, 3633, 3715, 3721, 3736, 3744, 3748, 3750, 3756, 3761,
3781, 3912, 4239, 4347, 4681, 4695, 4697, 4745, 4785, 4799, 4801, 4823,
4881, 5760, 5901, 5997, 6313, 7405, 8024, 8026, 8028, 8030, 8117, 8125,
8133, 8181, 8468, 8485, 8487, 8489, 8494, 8527, 11311, 11359, 11687, 11695,
11703, 11711, 11719, 11727, 11735, 12448, 12539, 43010, 43014, 43019, 43587,
43696, 43713, 64286, 64297, 64311, 64317, 64319, 64322, 64325, 65141];
var i, j, start, end;
for (i = 0; i < singles.length; i++) {
result[singles[i]] = true;
}
var ranges = [[0, 47], [58, 64], [91, 94], [123, 169], [171, 177], [182, 184], [706, 709],
[722, 735], [741, 747], [751, 879], [888, 889], [894, 901], [1154, 1161],
[1318, 1328], [1367, 1368], [1370, 1376], [1416, 1487], [1515, 1519], [1523, 1568],
[1611, 1631], [1642, 1645], [1750, 1764], [1767, 1773], [1789, 1790], [1792, 1807],
[1840, 1868], [1958, 1968], [1970, 1983], [2027, 2035], [2038, 2041], [2043, 2047],
[2070, 2073], [2075, 2083], [2085, 2087], [2089, 2307], [2362, 2364], [2366, 2383],
[2385, 2391], [2402, 2405], [2419, 2424], [2432, 2436], [2445, 2446], [2449, 2450],
[2483, 2485], [2490, 2492], [2494, 2509], [2511, 2523], [2530, 2533], [2546, 2547],
[2554, 2564], [2571, 2574], [2577, 2578], [2618, 2648], [2655, 2661], [2672, 2673],
[2677, 2692], [2746, 2748], [2750, 2767], [2769, 2783], [2786, 2789], [2800, 2820],
[2829, 2830], [2833, 2834], [2874, 2876], [2878, 2907], [2914, 2917], [2930, 2946],
[2955, 2957], [2966, 2968], [2976, 2978], [2981, 2983], [2987, 2989], [3002, 3023],
[3025, 3045], [3059, 3076], [3130, 3132], [3134, 3159], [3162, 3167], [3170, 3173],
[3184, 3191], [3199, 3204], [3258, 3260], [3262, 3293], [3298, 3301], [3312, 3332],
[3386, 3388], [3390, 3423], [3426, 3429], [3446, 3449], [3456, 3460], [3479, 3481],
[3518, 3519], [3527, 3584], [3636, 3647], [3655, 3663], [3674, 3712], [3717, 3718],
[3723, 3724], [3726, 3731], [3752, 3753], [3764, 3772], [3774, 3775], [3783, 3791],
[3802, 3803], [3806, 3839], [3841, 3871], [3892, 3903], [3949, 3975], [3980, 4095],
[4139, 4158], [4170, 4175], [4182, 4185], [4190, 4192], [4194, 4196], [4199, 4205],
[4209, 4212], [4226, 4237], [4250, 4255], [4294, 4303], [4349, 4351], [4686, 4687],
[4702, 4703], [4750, 4751], [4790, 4791], [4806, 4807], [4886, 4887], [4955, 4968],
[4989, 4991], [5008, 5023], [5109, 5120], [5741, 5742], [5787, 5791], [5867, 5869],
[5873, 5887], [5906, 5919], [5938, 5951], [5970, 5983], [6001, 6015], [6068, 6102],
[6104, 6107], [6109, 6111], [6122, 6127], [6138, 6159], [6170, 6175], [6264, 6271],
[6315, 6319], [6390, 6399], [6429, 6469], [6510, 6511], [6517, 6527], [6572, 6592],
[6600, 6607], [6619, 6655], [6679, 6687], [6741, 6783], [6794, 6799], [6810, 6822],
[6824, 6916], [6964, 6980], [6988, 6991], [7002, 7042], [7073, 7085], [7098, 7167],
[7204, 7231], [7242, 7244], [7294, 7400], [7410, 7423], [7616, 7679], [7958, 7959],
[7966, 7967], [8006, 8007], [8014, 8015], [8062, 8063], [8127, 8129], [8141, 8143],
[8148, 8149], [8156, 8159], [8173, 8177], [8189, 8303], [8306, 8307], [8314, 8318],
[8330, 8335], [8341, 8449], [8451, 8454], [8456, 8457], [8470, 8472], [8478, 8483],
[8506, 8507], [8512, 8516], [8522, 8525], [8586, 9311], [9372, 9449], [9472, 10101],
[10132, 11263], [11493, 11498], [11503, 11516], [11518, 11519], [11558, 11567],
[11622, 11630], [11632, 11647], [11671, 11679], [11743, 11822], [11824, 12292],
[12296, 12320], [12330, 12336], [12342, 12343], [12349, 12352], [12439, 12444],
[12544, 12548], [12590, 12592], [12687, 12689], [12694, 12703], [12728, 12783],
[12800, 12831], [12842, 12880], [12896, 12927], [12938, 12976], [12992, 13311],
[19894, 19967], [40908, 40959], [42125, 42191], [42238, 42239], [42509, 42511],
[42540, 42559], [42592, 42593], [42607, 42622], [42648, 42655], [42736, 42774],
[42784, 42785], [42889, 42890], [42893, 43002], [43043, 43055], [43062, 43071],
[43124, 43137], [43188, 43215], [43226, 43249], [43256, 43258], [43260, 43263],
[43302, 43311], [43335, 43359], [43389, 43395], [43443, 43470], [43482, 43519],
[43561, 43583], [43596, 43599], [43610, 43615], [43639, 43641], [43643, 43647],
[43698, 43700], [43703, 43704], [43710, 43711], [43715, 43738], [43742, 43967],
[44003, 44015], [44026, 44031], [55204, 55215], [55239, 55242], [55292, 55295],
[57344, 63743], [64046, 64047], [64110, 64111], [64218, 64255], [64263, 64274],
[64280, 64284], [64434, 64466], [64830, 64847], [64912, 64913], [64968, 65007],
[65020, 65135], [65277, 65295], [65306, 65312], [65339, 65344], [65371, 65381],
[65471, 65473], [65480, 65481], [65488, 65489], [65496, 65497]];
for (i = 0; i < ranges.length; i++) {
start = ranges[i][0];
end = ranges[i][1];
for (j = start; j <= end; j++) {
result[j] = true;
}
}
return result;
})();
function splitQuery(query) {
var result = [];
var start = -1;
for (var i = 0; i < query.length; i++) {
if (splitChars[query.charCodeAt(i)]) {
if (start !== -1) {
result.push(query.slice(start, i));
start = -1;
}
} else if (start === -1) {
start = i;
}
}
if (start !== -1) {
result.push(query.slice(start));
}
return result;
}
/**
* Search Module
*/
var Search = {
_index : null,
_queued_query : null,
_pulse_status : -1,
init : function() {
var params = $.getQueryParameters();
if (params.q) {
var query = params.q[0];
$('input[name="q"]')[0].value = query;
this.performSearch(query);
}
},
loadIndex : function(url) {
$.ajax({type: "GET", url: url, data: null,
dataType: "script", cache: true,
complete: function(jqxhr, textstatus) {
if (textstatus != "success") {
document.getElementById("searchindexloader").src = url;
}
}});
},
setIndex : function(index) {
var q;
this._index = index;
if ((q = this._queued_query) !== null) {
this._queued_query = null;
Search.query(q);
}
},
hasIndex : function() {
return this._index !== null;
},
deferQuery : function(query) {
this._queued_query = query;
},
stopPulse : function() {
this._pulse_status = 0;
},
startPulse : function() {
if (this._pulse_status >= 0)
return;
function pulse() {
var i;
Search._pulse_status = (Search._pulse_status + 1) % 4;
var dotString = '';
for (i = 0; i < Search._pulse_status; i++)
dotString += '.';
Search.dots.text(dotString);
if (Search._pulse_status > -1)
window.setTimeout(pulse, 500);
}
pulse();
},
/**
* perform a search for something (or wait until index is loaded)
*/
performSearch : function(query) {
// create the required interface elements
this.out = $('#search-results');
this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
this.dots = $('<span></span>').appendTo(this.title);
this.status = $('<p style="display: none"></p>').appendTo(this.out);
this.output = $('<ul class="search"/>').appendTo(this.out);
$('#search-progress').text(_('Preparing search...'));
this.startPulse();
// index already loaded, the browser was quick!
if (this.hasIndex())
this.query(query);
else
this.deferQuery(query);
},
/**
* execute search (requires search index to be loaded)
*/
query : function(query) {
var i;
var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];
// stem the searchterms and add them to the correct list
var stemmer = new Stemmer();
var searchterms = [];
var excluded = [];
var hlterms = [];
var tmp = splitQuery(query);
var objectterms = [];
for (i = 0; i < tmp.length; i++) {
if (tmp[i] !== "") {
objectterms.push(tmp[i].toLowerCase());
}
if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
tmp[i] === "") {
// skip this "word"
continue;
}
// stem the word
var word = stemmer.stemWord(tmp[i].toLowerCase());
// prevent stemmer from cutting word smaller than two chars
if(word.length < 3 && tmp[i].length >= 3) {
word = tmp[i];
}
var toAppend;
// select the correct list
if (word[0] == '-') {
toAppend = excluded;
word = word.substr(1);
}
else {
toAppend = searchterms;
hlterms.push(tmp[i].toLowerCase());
}
// only add if not already in the list
if (!$u.contains(toAppend, word))
toAppend.push(word);
}
var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
// console.debug('SEARCH: searching for:');
// console.info('required: ', searchterms);
// console.info('excluded: ', excluded);
// prepare search
var terms = this._index.terms;
var titleterms = this._index.titleterms;
// array of [filename, title, anchor, descr, score]
var results = [];
$('#search-progress').empty();
// lookup as object
for (i = 0; i < objectterms.length; i++) {
var others = [].concat(objectterms.slice(0, i),
objectterms.slice(i+1, objectterms.length));
results = results.concat(this.performObjectSearch(objectterms[i], others));
}
// lookup as search terms in fulltext
results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
// let the scorer override scores with a custom scoring function
if (Scorer.score) {
for (i = 0; i < results.length; i++)
results[i][4] = Scorer.score(results[i]);
}
// now sort the results by score (in opposite order of appearance, since the
// display function below uses pop() to retrieve items) and then
// alphabetically
results.sort(function(a, b) {
var left = a[4];
var right = b[4];
if (left > right) {
return 1;
} else if (left < right) {
return -1;
} else {
// same score: sort alphabetically
left = a[1].toLowerCase();
right = b[1].toLowerCase();
return (left > right) ? -1 : ((left < right) ? 1 : 0);
}
});
// for debugging
//Search.lastresults = results.slice(); // a copy
//console.info('search results:', Search.lastresults);
// print the results
var resultCount = results.length;
function displayNextItem() {
// results left, load the summary and display it
if (results.length) {
var item = results.pop();
var listItem = $('<li style="display:none"></li>');
if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
// dirhtml builder
var dirname = item[0] + '/';
if (dirname.match(/\/index\/$/)) {
dirname = dirname.substring(0, dirname.length-6);
} else if (dirname == 'index/') {
dirname = '';
}
listItem.append($('<a/>').attr('href',
DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
highlightstring + item[2]).html(item[1]));
} else {
// normal html builders
listItem.append($('<a/>').attr('href',
item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
highlightstring + item[2]).html(item[1]));
}
if (item[3]) {
listItem.append($('<span> (' + item[3] + ')</span>'));
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
var suffix = DOCUMENTATION_OPTIONS.SOURCELINK_SUFFIX;
if (suffix === undefined) {
suffix = '.txt';
}
$.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].slice(-suffix.length) === suffix ? '' : suffix),
dataType: "text",
complete: function(jqxhr, textstatus) {
var data = jqxhr.responseText;
if (data !== '' && data !== undefined) {
listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
}
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
}});
} else {
// no source available, just display title
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
}
}
// search finished, update title and status message
else {
Search.stopPulse();
Search.title.text(_('Search Results'));
if (!resultCount)
Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
else
Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
Search.status.fadeIn(500);
}
}
displayNextItem();
},
/**
* search for object names
*/
performObjectSearch : function(object, otherterms) {
var filenames = this._index.filenames;
var docnames = this._index.docnames;
var objects = this._index.objects;
var objnames = this._index.objnames;
var titles = this._index.titles;
var i;
var results = [];
for (var prefix in objects) {
for (var name in objects[prefix]) {
var fullname = (prefix ? prefix + '.' : '') + name;
if (fullname.toLowerCase().indexOf(object) > -1) {
var score = 0;
var parts = fullname.split('.');
// check for different match types: exact matches of full name or
// "last name" (i.e. last dotted part)
if (fullname == object || parts[parts.length - 1] == object) {
score += Scorer.objNameMatch;
// matches in last name
} else if (parts[parts.length - 1].indexOf(object) > -1) {
score += Scorer.objPartialMatch;
}
var match = objects[prefix][name];
var objname = objnames[match[1]][2];
var title = titles[match[0]];
// If more than one term searched for, we require other words to be
// found in the name/title/description
if (otherterms.length > 0) {
var haystack = (prefix + ' ' + name + ' ' +
objname + ' ' + title).toLowerCase();
var allfound = true;
for (i = 0; i < otherterms.length; i++) {
if (haystack.indexOf(otherterms[i]) == -1) {
allfound = false;
break;
}
}
if (!allfound) {
continue;
}
}
var descr = objname + _(', in ') + title;
var anchor = match[3];
if (anchor === '')
anchor = fullname;
else if (anchor == '-')
anchor = objnames[match[1]][1] + '-' + fullname;
// add custom score for some objects according to scorer
if (Scorer.objPrio.hasOwnProperty(match[2])) {
score += Scorer.objPrio[match[2]];
} else {
score += Scorer.objPrioDefault;
}
results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
}
}
}
return results;
},
/**
* search for full-text terms in the index
*/
performTermsSearch : function(searchterms, excluded, terms, titleterms) {
var docnames = this._index.docnames;
var filenames = this._index.filenames;
var titles = this._index.titles;
var i, j, file;
var fileMap = {};
var scoreMap = {};
var results = [];
// perform the search on the required terms
for (i = 0; i < searchterms.length; i++) {
var word = searchterms[i];
var files = [];
var _o = [
{files: terms[word], score: Scorer.term},
{files: titleterms[word], score: Scorer.title}
];
// no match but word was a required one
if ($u.every(_o, function(o){return o.files === undefined;})) {
break;
}
// found search word in contents
$u.each(_o, function(o) {
var _files = o.files;
if (_files === undefined)
return
if (_files.length === undefined)
_files = [_files];
files = files.concat(_files);
// set score for the word in each file to Scorer.term
for (j = 0; j < _files.length; j++) {
file = _files[j];
if (!(file in scoreMap))
scoreMap[file] = {}
scoreMap[file][word] = o.score;
}
});
// create the mapping
for (j = 0; j < files.length; j++) {
file = files[j];
if (file in fileMap)
fileMap[file].push(word);
else
fileMap[file] = [word];
}
}
// now check if the files don't contain excluded terms
for (file in fileMap) {
var valid = true;
// check if all requirements are matched
if (fileMap[file].length != searchterms.length)
continue;
// ensure that none of the excluded terms is in the search result
for (i = 0; i < excluded.length; i++) {
if (terms[excluded[i]] == file ||
titleterms[excluded[i]] == file ||
$u.contains(terms[excluded[i]] || [], file) ||
$u.contains(titleterms[excluded[i]] || [], file)) {
valid = false;
break;
}
}
// if we have still a valid result we can add it to the result list
if (valid) {
// select one (max) score for the file.
// for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
}
}
return results;
},
/**
* helper function to return a node containing the
* search summary for a given text. keywords is a list
* of stemmed words, hlwords is the list of normal, unstemmed
* words. the first one is used to find the occurrence, the
* latter for highlighting it.
*/
makeSearchSummary : function(text, keywords, hlwords) {
var textLower = text.toLowerCase();
var start = 0;
$.each(keywords, function() {
var i = textLower.indexOf(this.toLowerCase());
if (i > -1)
start = i;
});
start = Math.max(start - 120, 0);
var excerpt = ((start > 0) ? '...' : '') +
$.trim(text.substr(start, 240)) +
((start + 240 - text.length) ? '...' : '');
var rv = $('<div class="context"></div>').text(excerpt);
$.each(hlwords, function() {
rv = rv.highlightText(this, 'highlighted');
});
return rv;
}
};
$(document).ready(function() {
Search.init();
});

View File

@ -0,0 +1,159 @@
/*
* sidebar.js
* ~~~~~~~~~~
*
* This script makes the Sphinx sidebar collapsible.
*
* .sphinxsidebar contains .sphinxsidebarwrapper. This script adds
* in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton
* used to collapse and expand the sidebar.
*
* When the sidebar is collapsed the .sphinxsidebarwrapper is hidden
* and the width of the sidebar and the margin-left of the document
* are decreased. When the sidebar is expanded the opposite happens.
* This script saves a per-browser/per-session cookie used to
* remember the position of the sidebar among the pages.
* Once the browser is closed the cookie is deleted and the position
* reset to the default (expanded).
*
* :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
$(function() {
// global elements used by the functions.
// the 'sidebarbutton' element is defined as global after its
// creation, in the add_sidebar_button function
var bodywrapper = $('.bodywrapper');
var sidebar = $('.sphinxsidebar');
var sidebarwrapper = $('.sphinxsidebarwrapper');
// for some reason, the document has no sidebar; do not run into errors
if (!sidebar.length) return;
// original margin-left of the bodywrapper and width of the sidebar
// with the sidebar expanded
var bw_margin_expanded = bodywrapper.css('margin-left');
var ssb_width_expanded = sidebar.width();
// margin-left of the bodywrapper and width of the sidebar
// with the sidebar collapsed
var bw_margin_collapsed = '.8em';
var ssb_width_collapsed = '.8em';
// colors used by the current theme
var dark_color = $('.related').css('background-color');
var light_color = $('.document').css('background-color');
function sidebar_is_collapsed() {
return sidebarwrapper.is(':not(:visible)');
}
function toggle_sidebar() {
if (sidebar_is_collapsed())
expand_sidebar();
else
collapse_sidebar();
}
function collapse_sidebar() {
sidebarwrapper.hide();
sidebar.css('width', ssb_width_collapsed);
bodywrapper.css('margin-left', bw_margin_collapsed);
sidebarbutton.css({
'margin-left': '0',
'height': bodywrapper.height()
});
sidebarbutton.find('span').text('»');
sidebarbutton.attr('title', _('Expand sidebar'));
document.cookie = 'sidebar=collapsed';
}
function expand_sidebar() {
bodywrapper.css('margin-left', bw_margin_expanded);
sidebar.css('width', ssb_width_expanded);
sidebarwrapper.show();
sidebarbutton.css({
'margin-left': ssb_width_expanded-12,
'height': bodywrapper.height()
});
sidebarbutton.find('span').text('«');
sidebarbutton.attr('title', _('Collapse sidebar'));
document.cookie = 'sidebar=expanded';
}
function add_sidebar_button() {
sidebarwrapper.css({
'float': 'left',
'margin-right': '0',
'width': ssb_width_expanded - 28
});
// create the button
sidebar.append(
'<div id="sidebarbutton"><span>&laquo;</span></div>'
);
var sidebarbutton = $('#sidebarbutton');
light_color = sidebarbutton.css('background-color');
// find the height of the viewport to center the '<<' in the page
var viewport_height;
if (window.innerHeight)
viewport_height = window.innerHeight;
else
viewport_height = $(window).height();
sidebarbutton.find('span').css({
'display': 'block',
'margin-top': (viewport_height - sidebar.position().top - 20) / 2
});
sidebarbutton.click(toggle_sidebar);
sidebarbutton.attr('title', _('Collapse sidebar'));
sidebarbutton.css({
'color': '#FFFFFF',
'border-left': '1px solid ' + dark_color,
'font-size': '1.2em',
'cursor': 'pointer',
'height': bodywrapper.height(),
'padding-top': '1px',
'margin-left': ssb_width_expanded - 12
});
sidebarbutton.hover(
function () {
$(this).css('background-color', dark_color);
},
function () {
$(this).css('background-color', light_color);
}
);
}
function set_position_from_cookie() {
if (!document.cookie)
return;
var items = document.cookie.split(';');
for(var k=0; k<items.length; k++) {
var key_val = items[k].split('=');
var key = key_val[0].replace(/ /, ""); // strip leading spaces
if (key == 'sidebar') {
var value = key_val[1];
if ((value == 'collapsed') && (!sidebar_is_collapsed()))
collapse_sidebar();
else if ((value == 'expanded') && (sidebar_is_collapsed()))
expand_sidebar();
}
}
}
add_sidebar_button();
var sidebarbutton = $('#sidebarbutton');
set_position_from_cookie();
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,389 @@
body {
background-color: #222;
margin: 0;
padding: 0;
font-family: 'Georgia', serif;
font-size: 15px;
color: #eee;
}
div.footer {
border-top: 1px solid #111;
padding: 8px;
font-size: 11px;
text-align: center;
letter-spacing: 0.5px;
}
div.footer a {
color: #eee;
}
div.header {
margin: 0 -15px 0 -15px;
background: url(headerbg.png) repeat-x;
border-top: 6px solid #D20000;
}
div.relnav {
border-bottom: 1px solid #111;
background: url(navigation.png);
margin: 0 -15px 0 -15px;
padding: 2px 20px 0 28px;
line-height: 25px;
color: #aaa;
font-size: 12px;
text-align: center;
}
div.relnav a {
color: #eee;
font-weight: bold;
text-decoration: none;
}
div.relnav a:hover {
text-decoration: underline;
}
#content {
background-color: white;
color: #111;
border-bottom: 1px solid black;
background: url(watermark.png) center 0;
padding: 0 15px 0 15px;
margin: 0;
}
h1 {
margin: 0;
padding: 15px 0 0 0;
}
h1.heading {
margin: 0;
padding: 0;
height: 80px;
}
h1.heading:hover {
background: #222;
}
h1.heading a {
background: url(jinjabanner.png) no-repeat center 0;
display: block;
width: 100%;
height: 80px;
}
h1.heading a:focus {
-moz-outline: none;
outline: none;
}
h1.heading span {
display: none;
}
#jinjalogo {
background-image: url(jinjalogo.png);
background-repeat: no-repeat;
width: 400px;
height: 160px;
}
#contentwrapper {
max-width: 680px;
padding: 0 18px 20px 18px;
margin: 0 auto 0 auto;
border-right: 1px solid #eee;
border-left: 1px solid #eee;
background: url(watermark_blur.png) center -114px;
}
#contentwrapper h2,
#contentwrapper h2 a {
color: #222;
font-size: 24px;
margin: 20px 0 0 0;
}
#contentwrapper h3,
#contentwrapper h3 a {
color: #b41717;
font-size: 20px;
margin: 20px 0 0 0;
}
table.docutils {
border-collapse: collapse;
border: 2px solid #aaa;
margin: 0.5em 1.5em 0.5em 1.5em;
}
table.docutils td {
padding: 2px;
border: 1px solid #ddd;
}
p, li, dd, dt, blockquote {
color: #333;
}
blockquote {
margin: 10px 0 10px 20px;
}
p {
line-height: 20px;
margin-bottom: 0;
margin-top: 10px;
}
hr {
border-top: 1px solid #ccc;
border-bottom: 0;
border-right: 0;
border-left: 0;
margin-bottom: 10px;
margin-top: 20px;
}
dl {
margin-left: 10px;
}
li, dt {
margin-top: 5px;
}
dt {
font-weight: bold;
color: #000;
}
dd {
margin-top: 10px;
line-height: 20px;
}
th {
text-align: left;
padding: 3px;
background-color: #f2f2f2;
}
a {
color: #b41717;
}
a:hover {
color: #444;
}
pre {
background: #ededed url(metal.png);
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
padding: 5px;
font-size: 13px;
font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;
}
tt {
font-size: 13px;
font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;
color: black;
padding: 1px 2px 1px 2px;
background-color: #fafafa;
border-bottom: 1px solid #eee;
}
a.reference:hover tt {
border-bottom-color: #aaa;
}
cite {
/* abusing <cite>, it's generated by ReST for `x` */
font-size: 13px;
font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;
font-weight: bold;
font-style: normal;
}
div.admonition {
margin: 10px 0 10px 0;
padding: 10px 10px 10px 60px;
border: 1px solid #ccc;
}
div.admonition p.admonition-title {
background-color: #b41717;
color: white;
margin: -10px -10px 10px -60px;
padding: 4px 10px 4px 10px;
font-weight: bold;
font-size: 15px;
}
div.admonition p.admonition-title a {
color: white!important;
}
div.admonition-note {
background: url(note.png) no-repeat 10px 40px;
}
div.admonition-implementation {
background: url(implementation.png) no-repeat 10px 40px;
}
a.headerlink {
color: #B4B4B4!important;
font-size: 0.8em;
padding: 0 4px 0 4px;
text-decoration: none!important;
visibility: hidden;
}
h1:hover > a.headerlink,
h2:hover > a.headerlink,
h3:hover > a.headerlink,
h4:hover > a.headerlink,
h5:hover > a.headerlink,
h6:hover > a.headerlink,
dt:hover > a.headerlink {
visibility: visible;
}
a.headerlink:hover {
background-color: #B4B4B4;
color: #F0F0F0!important;
}
table.indextable {
width: 100%;
}
table.indextable td {
vertical-align: top;
width: 50%;
}
table.indextable dl dd {
font-size: 11px;
}
table.indextable dl dd a {
color: #000;
}
dl.function dt,
dl.class dt,
dl.exception dt,
dl.method dt,
dl.attribute dt {
font-weight: normal;
}
dt .descname {
font-weight: bold;
margin-right: 4px;
}
dt .descname, dt .descclassname {
padding: 0;
background: transparent;
border-bottom: 1px solid #111;
}
dt .descclassname {
margin-left: 2px;
}
dl dt big {
font-size: 100%;
}
ul.search {
margin: 10px 0 0 30px;
padding: 0;
}
ul.search li {
margin: 10px 0 0 0;
padding: 0;
}
ul.search div.context {
font-size: 12px;
padding: 4px 0 0 20px;
color: #888;
}
span.highlight {
background-color: #eee;
border: 1px solid #ccc;
}
#toc {
margin: 0 -17px 0 -17px;
display: none;
}
#toc h3 {
float: right;
margin: 5px 5px 0 0;
padding: 0;
font-size: 12px;
color: #777;
}
#toc h3:hover {
color: #333;
cursor: pointer;
}
.expandedtoc {
background: #222 url(darkmetal.png);
border-bottom: 1px solid #111;
outline-bottom: 1px solid #000;
padding: 5px;
}
.expandedtoc h3 {
color: #aaa;
margin: 0!important;
}
.expandedtoc h3:hover {
color: white!important;
}
#tod h3:hover {
color: white;
}
#toc a {
color: #ddd;
text-decoration: none;
}
#toc a:hover {
color: white;
text-decoration: underline;
}
#toc ul {
margin: 5px 0 12px 17px;
padding: 0 7px 0 7px;
}
#toc ul ul {
margin-bottom: 0;
}
#toc ul li {
margin: 2px 0 0 0;
}

View File

@ -0,0 +1 @@
Documentation.addTranslations({"locale": "fr", "messages": {"%(filename)s &#8212; %(docstitle)s": "%(filename)s &#8212; %(docstitle)s", "&#169; <a href=\"%(path)s\">Copyright</a> %(copyright)s.": "&#169; <a href=\"%(path)s\">Copyright</a> %(copyright)s.", "&#169; Copyright %(copyright)s.": "&#169; Copyright %(copyright)s.", ", in ": ", dans", "About these documents": "\u00c0 propos de ces documents", "Automatically generated list of changes in version %(version)s": "Liste auto-g\u00e9n\u00e9r\u00e9e des modifications dans la version %(version)s", "C API changes": "Modifications de l'API C", "Changes in Version %(version)s &#8212; %(docstitle)s": "Changements dans la version %(version)s &#8212; %(docstitle)s", "Collapse sidebar": "R\u00e9duire la barre lat\u00e9rale", "Complete Table of Contents": "Table des mati\u00e8res compl\u00e8te", "Contents": "Contenu", "Copyright": "Copyright", "Created using <a href=\"http://sphinx-doc.org/\">Sphinx</a> %(sphinx_version)s.": "Cr\u00e9\u00e9 avec <a href=\"http://sphinx-doc.org/\">Sphinx</a> %(sphinx_version)s.", "Expand sidebar": "Agrandir la barre lat\u00e9rale", "From here you can search these documents. Enter your search\n words into the box below and click \"search\". Note that the search\n function will automatically search for all of the words. Pages\n containing fewer words won't appear in the result list.": "Vous pouvez effectuer une recherche au sein des documents. Saisissez les termes\nde votre recherche dans le champs ci-dessous et cliquez sur \"rechercher\". Notez que la fonctionnalit\u00e9 de recherche\nva automatiquement chercher l'ensemble des mots. Les pages\ncontenant moins de mots n'appara\u00eetront pas dans la liste des r\u00e9sultats.", "Full index on one page": "Index complet sur une seule page", "General Index": "Index g\u00e9n\u00e9ral", "Global Module Index": "Index g\u00e9n\u00e9ral des modules", "Go": "Go", "Hide Search Matches": "Cacher les r\u00e9sultats de la recherche", "Index": "Index", "Index &ndash; %(key)s": "Index &ndash; %(key)s", "Index pages by letter": "Indexer les pages par lettre", "Indices and tables:": "Indices et Tables :", "Last updated on %(last_updated)s.": "Mis \u00e0 jour le %(last_updated)s.", "Library changes": "Modifications de la biblioth\u00e8que", "Navigation": "Navigation", "Next topic": "Sujet suivant", "Other changes": "Autres modifications", "Overview": "R\u00e9sum\u00e9", "Permalink to this definition": "Lien permanent vers cette d\u00e9finition", "Permalink to this headline": "Lien permanent vers ce titre", "Please activate JavaScript to enable the search\n functionality.": "Veuillez activer le JavaScript pour que la recherche fonctionne.", "Preparing search...": "Pr\u00e9paration de la recherche...", "Previous topic": "Sujet pr\u00e9c\u00e9dent", "Quick search": "Recherche rapide", "Search": "Recherche", "Search Page": "Page de recherche", "Search Results": "R\u00e9sultats de la recherche", "Search finished, found %s page(s) matching the search query.": "La recherche est finie, %s page(s) trouv\u00e9e(s) qui corresponde(nt) \u00e0 la recherche.", "Search within %(docstitle)s": "Recherchez dans %(docstitle)s", "Searching": "Recherche en cours", "Show Source": "Montrer le code source", "Table Of Contents": "Table des Mati\u00e8res", "This Page": "Cette page", "Welcome! This is": "Bienvenue ! Ceci est", "Your search did not match any documents. Please make sure that all words are spelled correctly and that you've selected enough categories.": "Votre recherche ne correspond \u00e0 aucun document. Veuillez v\u00e9rifier que les mots sont correctement orthographi\u00e9s et que vous avez s\u00e9lectionn\u00e9 assez de cat\u00e9gories.", "all functions, classes, terms": "toutes les fonctions, classes, termes", "can be huge": "peut \u00eatre \u00e9norme", "last updated": "derni\u00e8re modification", "lists all sections and subsections": "lister l'ensemble des sections et sous-sections", "next chapter": "Chapitre suivant", "previous chapter": "Chapitre pr\u00e9c\u00e9dent", "quick access to all modules": "acc\u00e8s rapide \u00e0 l'ensemble des modules", "search": "rechercher", "search this documentation": "rechercher dans cette documentation", "the documentation for": "la documentation pour"}, "plural_expr": "(n > 1)"});

View File

@ -0,0 +1,1548 @@
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
// Naked function reference for surrogate-prototype-swapping.
var Ctor = function(){};
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.8.3';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
var cb = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
};
_.iteratee = function(value, context) {
return cb(value, context, Infinity);
};
// An internal function for creating assigner functions.
var createAssigner = function(keysFunc, undefinedOnly) {
return function(obj) {
var length = arguments.length;
if (length < 2 || obj == null) return obj;
for (var index = 1; index < length; index++) {
var source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
};
// An internal function for creating a new object that inherits from another.
var baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
};
var property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
};
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length);
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Create a reducing function iterating left or right.
function createReduce(dir) {
// Optimized iterator function as using arguments.length
// in the main function will deoptimize the, see #1991.
function iterator(obj, iteratee, memo, keys, index, length) {
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
}
return function(obj, iteratee, memo, context) {
iteratee = optimizeCb(iteratee, context, 4);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1;
// Determine the initial value if none is provided.
if (arguments.length < 3) {
memo = obj[keys ? keys[index] : index];
index += dir;
}
return iterator(obj, iteratee, memo, keys, index, length);
};
}
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = createReduce(1);
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = createReduce(-1);
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var key;
if (isArrayLike(obj)) {
key = _.findIndex(obj, predicate, context);
} else {
key = _.findKey(obj, predicate, context);
}
if (key !== void 0 && key !== -1) return obj[key];
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
predicate = cb(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(cb(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given item (using `===`).
// Aliased as `includes` and `include`.
_.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return _.indexOf(obj, item, fromIndex) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matcher(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matcher(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/FisherYates_shuffle).
_.shuffle = function(obj) {
var set = isArrayLike(obj) ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = cb(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (isArrayLike(obj)) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = cb(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, startIndex) {
var output = [], idx = 0;
for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
//flatten current level of array or arguments object
if (!shallow) value = flatten(value, shallow, strict);
var j = 0, len = value.length;
output.length += len;
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!_.contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!_.contains(result, value)) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = getLength(array); i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(arguments, true, true, 1);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
return _.unzip(arguments);
};
// Complement of _.zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices
_.unzip = function(array) {
var length = array && _.max(array, getLength).length || 0;
var result = Array(length);
for (var index = 0; index < length; index++) {
result[index] = _.pluck(array, index);
}
return result;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
var result = {};
for (var i = 0, length = getLength(list); i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Generator function to create the findIndex and findLastIndex functions
function createPredicateIndexFinder(dir) {
return function(array, predicate, context) {
predicate = cb(predicate, context);
var length = getLength(array);
var index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
return -1;
};
}
// Returns the first index on an array-like that passes a predicate test
_.findIndex = createPredicateIndexFinder(1);
_.findLastIndex = createPredicateIndexFinder(-1);
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = getLength(array);
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Generator function to create the indexOf and lastIndexOf functions
function createIndexFinder(dir, predicateFind, sortedIndex) {
return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), _.isNaN);
return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
return -1;
};
}
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
_.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Determines whether to execute a function as a constructor
// or a normal function with the provided arguments
var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
var args = slice.call(arguments, 2);
var bound = function() {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
var bound = function() {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = _.partial(_.delay, _, 1);
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed on and after the Nth call.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed up to (but not including) the Nth call.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
}
if (times <= 1) func = null;
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
function collectNonEnumProps(obj, keys) {
var nonEnumIdx = nonEnumerableProps.length;
var constructor = obj.constructor;
var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
// Constructor is a special case.
var prop = 'constructor';
if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
while (nonEnumIdx--) {
prop = nonEnumerableProps[nonEnumIdx];
if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
keys.push(prop);
}
}
}
// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve all the property names of an object.
_.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Returns the results of applying the iteratee to each element of the object
// In contrast to _.map it returns an object
_.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = _.keys(obj),
length = keys.length,
results = {},
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys[index];
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = createAssigner(_.allKeys);
// Assigns a given object with all the own properties in the passed-in object(s)
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
_.extendOwn = _.assign = createAssigner(_.keys);
// Returns the first key on an object that passes a predicate test
_.findKey = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = _.keys(obj), key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (predicate(obj[key], key, obj)) return key;
}
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(object, oiteratee, context) {
var result = {}, obj = object, iteratee, keys;
if (obj == null) return result;
if (_.isFunction(oiteratee)) {
keys = _.allKeys(obj);
iteratee = optimizeCb(oiteratee, context);
} else {
keys = flatten(arguments, false, false, 1);
iteratee = function(value, key, obj) { return key in obj; };
obj = Object(obj);
}
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(flatten(arguments, false, false, 1), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = createAssigner(_.allKeys, true);
// Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
_.create = function(prototype, props) {
var result = baseCreate(prototype);
if (props) _.extendOwn(result, props);
return result;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Returns whether an object has a given set of `key:value` pairs.
_.isMatch = function(object, attrs) {
var keys = _.keys(attrs), length = keys.length;
if (object == null) return !length;
var obj = Object(object);
for (var i = 0; i < length; i++) {
var key = keys[i];
if (attrs[key] !== obj[key] || !(key in obj)) return false;
}
return true;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
var areArrays = className === '[object Array]';
if (!areArrays) {
if (typeof a != 'object' || typeof b != 'object') return false;
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_.keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
return _.keys(obj).length === 0;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), and in Safari 8 (#1929).
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
// Predicate-generating functions. Often useful outside of Underscore.
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = property;
// Generates a function for a given object that returns a given property.
_.propertyOf = function(obj) {
return obj == null ? function(){} : function(key) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of
// `key:value` pairs.
_.matcher = _.matches = function(attrs) {
attrs = _.extendOwn({}, attrs);
return function(obj) {
return _.isMatch(obj, attrs);
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = optimizeCb(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property, fallback) {
var value = object == null ? void 0 : object[property];
if (value === void 0) {
value = fallback;
}
return _.isFunction(value) ? value.call(object) : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(instance, obj) {
return instance._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// Provide unwrapping proxy for some methods used in engine operations
// such as arithmetic and JSON stringification.
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
_.prototype.toString = function() {
return '' + this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 B

View File

@ -0,0 +1,808 @@
/*
* websupport.js
* ~~~~~~~~~~~~~
*
* sphinx.websupport utilities for all documentation.
*
* :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
(function($) {
$.fn.autogrow = function() {
return this.each(function() {
var textarea = this;
$.fn.autogrow.resize(textarea);
$(textarea)
.focus(function() {
textarea.interval = setInterval(function() {
$.fn.autogrow.resize(textarea);
}, 500);
})
.blur(function() {
clearInterval(textarea.interval);
});
});
};
$.fn.autogrow.resize = function(textarea) {
var lineHeight = parseInt($(textarea).css('line-height'), 10);
var lines = textarea.value.split('\n');
var columns = textarea.cols;
var lineCount = 0;
$.each(lines, function() {
lineCount += Math.ceil(this.length / columns) || 1;
});
var height = lineHeight * (lineCount + 1);
$(textarea).css('height', height);
};
})(jQuery);
(function($) {
var comp, by;
function init() {
initEvents();
initComparator();
}
function initEvents() {
$(document).on("click", 'a.comment-close', function(event) {
event.preventDefault();
hide($(this).attr('id').substring(2));
});
$(document).on("click", 'a.vote', function(event) {
event.preventDefault();
handleVote($(this));
});
$(document).on("click", 'a.reply', function(event) {
event.preventDefault();
openReply($(this).attr('id').substring(2));
});
$(document).on("click", 'a.close-reply', function(event) {
event.preventDefault();
closeReply($(this).attr('id').substring(2));
});
$(document).on("click", 'a.sort-option', function(event) {
event.preventDefault();
handleReSort($(this));
});
$(document).on("click", 'a.show-proposal', function(event) {
event.preventDefault();
showProposal($(this).attr('id').substring(2));
});
$(document).on("click", 'a.hide-proposal', function(event) {
event.preventDefault();
hideProposal($(this).attr('id').substring(2));
});
$(document).on("click", 'a.show-propose-change', function(event) {
event.preventDefault();
showProposeChange($(this).attr('id').substring(2));
});
$(document).on("click", 'a.hide-propose-change', function(event) {
event.preventDefault();
hideProposeChange($(this).attr('id').substring(2));
});
$(document).on("click", 'a.accept-comment', function(event) {
event.preventDefault();
acceptComment($(this).attr('id').substring(2));
});
$(document).on("click", 'a.delete-comment', function(event) {
event.preventDefault();
deleteComment($(this).attr('id').substring(2));
});
$(document).on("click", 'a.comment-markup', function(event) {
event.preventDefault();
toggleCommentMarkupBox($(this).attr('id').substring(2));
});
}
/**
* Set comp, which is a comparator function used for sorting and
* inserting comments into the list.
*/
function setComparator() {
// If the first three letters are "asc", sort in ascending order
// and remove the prefix.
if (by.substring(0,3) == 'asc') {
var i = by.substring(3);
comp = function(a, b) { return a[i] - b[i]; };
} else {
// Otherwise sort in descending order.
comp = function(a, b) { return b[by] - a[by]; };
}
// Reset link styles and format the selected sort option.
$('a.sel').attr('href', '#').removeClass('sel');
$('a.by' + by).removeAttr('href').addClass('sel');
}
/**
* Create a comp function. If the user has preferences stored in
* the sortBy cookie, use those, otherwise use the default.
*/
function initComparator() {
by = 'rating'; // Default to sort by rating.
// If the sortBy cookie is set, use that instead.
if (document.cookie.length > 0) {
var start = document.cookie.indexOf('sortBy=');
if (start != -1) {
start = start + 7;
var end = document.cookie.indexOf(";", start);
if (end == -1) {
end = document.cookie.length;
by = unescape(document.cookie.substring(start, end));
}
}
}
setComparator();
}
/**
* Show a comment div.
*/
function show(id) {
$('#ao' + id).hide();
$('#ah' + id).show();
var context = $.extend({id: id}, opts);
var popup = $(renderTemplate(popupTemplate, context)).hide();
popup.find('textarea[name="proposal"]').hide();
popup.find('a.by' + by).addClass('sel');
var form = popup.find('#cf' + id);
form.submit(function(event) {
event.preventDefault();
addComment(form);
});
$('#s' + id).after(popup);
popup.slideDown('fast', function() {
getComments(id);
});
}
/**
* Hide a comment div.
*/
function hide(id) {
$('#ah' + id).hide();
$('#ao' + id).show();
var div = $('#sc' + id);
div.slideUp('fast', function() {
div.remove();
});
}
/**
* Perform an ajax request to get comments for a node
* and insert the comments into the comments tree.
*/
function getComments(id) {
$.ajax({
type: 'GET',
url: opts.getCommentsURL,
data: {node: id},
success: function(data, textStatus, request) {
var ul = $('#cl' + id);
var speed = 100;
$('#cf' + id)
.find('textarea[name="proposal"]')
.data('source', data.source);
if (data.comments.length === 0) {
ul.html('<li>No comments yet.</li>');
ul.data('empty', true);
} else {
// If there are comments, sort them and put them in the list.
var comments = sortComments(data.comments);
speed = data.comments.length * 100;
appendComments(comments, ul);
ul.data('empty', false);
}
$('#cn' + id).slideUp(speed + 200);
ul.slideDown(speed);
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem retrieving the comments.');
},
dataType: 'json'
});
}
/**
* Add a comment via ajax and insert the comment into the comment tree.
*/
function addComment(form) {
var node_id = form.find('input[name="node"]').val();
var parent_id = form.find('input[name="parent"]').val();
var text = form.find('textarea[name="comment"]').val();
var proposal = form.find('textarea[name="proposal"]').val();
if (text == '') {
showError('Please enter a comment.');
return;
}
// Disable the form that is being submitted.
form.find('textarea,input').attr('disabled', 'disabled');
// Send the comment to the server.
$.ajax({
type: "POST",
url: opts.addCommentURL,
dataType: 'json',
data: {
node: node_id,
parent: parent_id,
text: text,
proposal: proposal
},
success: function(data, textStatus, error) {
// Reset the form.
if (node_id) {
hideProposeChange(node_id);
}
form.find('textarea')
.val('')
.add(form.find('input'))
.removeAttr('disabled');
var ul = $('#cl' + (node_id || parent_id));
if (ul.data('empty')) {
$(ul).empty();
ul.data('empty', false);
}
insertComment(data.comment);
var ao = $('#ao' + node_id);
ao.find('img').attr({'src': opts.commentBrightImage});
if (node_id) {
// if this was a "root" comment, remove the commenting box
// (the user can get it back by reopening the comment popup)
$('#ca' + node_id).slideUp();
}
},
error: function(request, textStatus, error) {
form.find('textarea,input').removeAttr('disabled');
showError('Oops, there was a problem adding the comment.');
}
});
}
/**
* Recursively append comments to the main comment list and children
* lists, creating the comment tree.
*/
function appendComments(comments, ul) {
$.each(comments, function() {
var div = createCommentDiv(this);
ul.append($(document.createElement('li')).html(div));
appendComments(this.children, div.find('ul.comment-children'));
// To avoid stagnating data, don't store the comments children in data.
this.children = null;
div.data('comment', this);
});
}
/**
* After adding a new comment, it must be inserted in the correct
* location in the comment tree.
*/
function insertComment(comment) {
var div = createCommentDiv(comment);
// To avoid stagnating data, don't store the comments children in data.
comment.children = null;
div.data('comment', comment);
var ul = $('#cl' + (comment.node || comment.parent));
var siblings = getChildren(ul);
var li = $(document.createElement('li'));
li.hide();
// Determine where in the parents children list to insert this comment.
for(i=0; i < siblings.length; i++) {
if (comp(comment, siblings[i]) <= 0) {
$('#cd' + siblings[i].id)
.parent()
.before(li.html(div));
li.slideDown('fast');
return;
}
}
// If we get here, this comment rates lower than all the others,
// or it is the only comment in the list.
ul.append(li.html(div));
li.slideDown('fast');
}
function acceptComment(id) {
$.ajax({
type: 'POST',
url: opts.acceptCommentURL,
data: {id: id},
success: function(data, textStatus, request) {
$('#cm' + id).fadeOut('fast');
$('#cd' + id).removeClass('moderate');
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem accepting the comment.');
}
});
}
function deleteComment(id) {
$.ajax({
type: 'POST',
url: opts.deleteCommentURL,
data: {id: id},
success: function(data, textStatus, request) {
var div = $('#cd' + id);
if (data == 'delete') {
// Moderator mode: remove the comment and all children immediately
div.slideUp('fast', function() {
div.remove();
});
return;
}
// User mode: only mark the comment as deleted
div
.find('span.user-id:first')
.text('[deleted]').end()
.find('div.comment-text:first')
.text('[deleted]').end()
.find('#cm' + id + ', #dc' + id + ', #ac' + id + ', #rc' + id +
', #sp' + id + ', #hp' + id + ', #cr' + id + ', #rl' + id)
.remove();
var comment = div.data('comment');
comment.username = '[deleted]';
comment.text = '[deleted]';
div.data('comment', comment);
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem deleting the comment.');
}
});
}
function showProposal(id) {
$('#sp' + id).hide();
$('#hp' + id).show();
$('#pr' + id).slideDown('fast');
}
function hideProposal(id) {
$('#hp' + id).hide();
$('#sp' + id).show();
$('#pr' + id).slideUp('fast');
}
function showProposeChange(id) {
$('#pc' + id).hide();
$('#hc' + id).show();
var textarea = $('#pt' + id);
textarea.val(textarea.data('source'));
$.fn.autogrow.resize(textarea[0]);
textarea.slideDown('fast');
}
function hideProposeChange(id) {
$('#hc' + id).hide();
$('#pc' + id).show();
var textarea = $('#pt' + id);
textarea.val('').removeAttr('disabled');
textarea.slideUp('fast');
}
function toggleCommentMarkupBox(id) {
$('#mb' + id).toggle();
}
/** Handle when the user clicks on a sort by link. */
function handleReSort(link) {
var classes = link.attr('class').split(/\s+/);
for (var i=0; i<classes.length; i++) {
if (classes[i] != 'sort-option') {
by = classes[i].substring(2);
}
}
setComparator();
// Save/update the sortBy cookie.
var expiration = new Date();
expiration.setDate(expiration.getDate() + 365);
document.cookie= 'sortBy=' + escape(by) +
';expires=' + expiration.toUTCString();
$('ul.comment-ul').each(function(index, ul) {
var comments = getChildren($(ul), true);
comments = sortComments(comments);
appendComments(comments, $(ul).empty());
});
}
/**
* Function to process a vote when a user clicks an arrow.
*/
function handleVote(link) {
if (!opts.voting) {
showError("You'll need to login to vote.");
return;
}
var id = link.attr('id');
if (!id) {
// Didn't click on one of the voting arrows.
return;
}
// If it is an unvote, the new vote value is 0,
// Otherwise it's 1 for an upvote, or -1 for a downvote.
var value = 0;
if (id.charAt(1) != 'u') {
value = id.charAt(0) == 'u' ? 1 : -1;
}
// The data to be sent to the server.
var d = {
comment_id: id.substring(2),
value: value
};
// Swap the vote and unvote links.
link.hide();
$('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id)
.show();
// The div the comment is displayed in.
var div = $('div#cd' + d.comment_id);
var data = div.data('comment');
// If this is not an unvote, and the other vote arrow has
// already been pressed, unpress it.
if ((d.value !== 0) && (data.vote === d.value * -1)) {
$('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide();
$('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show();
}
// Update the comments rating in the local data.
data.rating += (data.vote === 0) ? d.value : (d.value - data.vote);
data.vote = d.value;
div.data('comment', data);
// Change the rating text.
div.find('.rating:first')
.text(data.rating + ' point' + (data.rating == 1 ? '' : 's'));
// Send the vote information to the server.
$.ajax({
type: "POST",
url: opts.processVoteURL,
data: d,
error: function(request, textStatus, error) {
showError('Oops, there was a problem casting that vote.');
}
});
}
/**
* Open a reply form used to reply to an existing comment.
*/
function openReply(id) {
// Swap out the reply link for the hide link
$('#rl' + id).hide();
$('#cr' + id).show();
// Add the reply li to the children ul.
var div = $(renderTemplate(replyTemplate, {id: id})).hide();
$('#cl' + id)
.prepend(div)
// Setup the submit handler for the reply form.
.find('#rf' + id)
.submit(function(event) {
event.preventDefault();
addComment($('#rf' + id));
closeReply(id);
})
.find('input[type=button]')
.click(function() {
closeReply(id);
});
div.slideDown('fast', function() {
$('#rf' + id).find('textarea').focus();
});
}
/**
* Close the reply form opened with openReply.
*/
function closeReply(id) {
// Remove the reply div from the DOM.
$('#rd' + id).slideUp('fast', function() {
$(this).remove();
});
// Swap out the hide link for the reply link
$('#cr' + id).hide();
$('#rl' + id).show();
}
/**
* Recursively sort a tree of comments using the comp comparator.
*/
function sortComments(comments) {
comments.sort(comp);
$.each(comments, function() {
this.children = sortComments(this.children);
});
return comments;
}
/**
* Get the children comments from a ul. If recursive is true,
* recursively include childrens' children.
*/
function getChildren(ul, recursive) {
var children = [];
ul.children().children("[id^='cd']")
.each(function() {
var comment = $(this).data('comment');
if (recursive)
comment.children = getChildren($(this).find('#cl' + comment.id), true);
children.push(comment);
});
return children;
}
/** Create a div to display a comment in. */
function createCommentDiv(comment) {
if (!comment.displayed && !opts.moderator) {
return $('<div class="moderate">Thank you! Your comment will show up '
+ 'once it is has been approved by a moderator.</div>');
}
// Prettify the comment rating.
comment.pretty_rating = comment.rating + ' point' +
(comment.rating == 1 ? '' : 's');
// Make a class (for displaying not yet moderated comments differently)
comment.css_class = comment.displayed ? '' : ' moderate';
// Create a div for this comment.
var context = $.extend({}, opts, comment);
var div = $(renderTemplate(commentTemplate, context));
// If the user has voted on this comment, highlight the correct arrow.
if (comment.vote) {
var direction = (comment.vote == 1) ? 'u' : 'd';
div.find('#' + direction + 'v' + comment.id).hide();
div.find('#' + direction + 'u' + comment.id).show();
}
if (opts.moderator || comment.text != '[deleted]') {
div.find('a.reply').show();
if (comment.proposal_diff)
div.find('#sp' + comment.id).show();
if (opts.moderator && !comment.displayed)
div.find('#cm' + comment.id).show();
if (opts.moderator || (opts.username == comment.username))
div.find('#dc' + comment.id).show();
}
return div;
}
/**
* A simple template renderer. Placeholders such as <%id%> are replaced
* by context['id'] with items being escaped. Placeholders such as <#id#>
* are not escaped.
*/
function renderTemplate(template, context) {
var esc = $(document.createElement('div'));
function handle(ph, escape) {
var cur = context;
$.each(ph.split('.'), function() {
cur = cur[this];
});
return escape ? esc.text(cur || "").html() : cur;
}
return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
return handle(arguments[2], arguments[1] == '%' ? true : false);
});
}
/** Flash an error message briefly. */
function showError(message) {
$(document.createElement('div')).attr({'class': 'popup-error'})
.append($(document.createElement('div'))
.attr({'class': 'error-message'}).text(message))
.appendTo('body')
.fadeIn("slow")
.delay(2000)
.fadeOut("slow");
}
/** Add a link the user uses to open the comments popup. */
$.fn.comment = function() {
return this.each(function() {
var id = $(this).attr('id').substring(1);
var count = COMMENT_METADATA[id];
var title = count + ' comment' + (count == 1 ? '' : 's');
var image = count > 0 ? opts.commentBrightImage : opts.commentImage;
var addcls = count == 0 ? ' nocomment' : '';
$(this)
.append(
$(document.createElement('a')).attr({
href: '#',
'class': 'sphinx-comment-open' + addcls,
id: 'ao' + id
})
.append($(document.createElement('img')).attr({
src: image,
alt: 'comment',
title: title
}))
.click(function(event) {
event.preventDefault();
show($(this).attr('id').substring(2));
})
)
.append(
$(document.createElement('a')).attr({
href: '#',
'class': 'sphinx-comment-close hidden',
id: 'ah' + id
})
.append($(document.createElement('img')).attr({
src: opts.closeCommentImage,
alt: 'close',
title: 'close'
}))
.click(function(event) {
event.preventDefault();
hide($(this).attr('id').substring(2));
})
);
});
};
var opts = {
processVoteURL: '/_process_vote',
addCommentURL: '/_add_comment',
getCommentsURL: '/_get_comments',
acceptCommentURL: '/_accept_comment',
deleteCommentURL: '/_delete_comment',
commentImage: '/static/_static/comment.png',
closeCommentImage: '/static/_static/comment-close.png',
loadingImage: '/static/_static/ajax-loader.gif',
commentBrightImage: '/static/_static/comment-bright.png',
upArrow: '/static/_static/up.png',
downArrow: '/static/_static/down.png',
upArrowPressed: '/static/_static/up-pressed.png',
downArrowPressed: '/static/_static/down-pressed.png',
voting: false,
moderator: false
};
if (typeof COMMENT_OPTIONS != "undefined") {
opts = jQuery.extend(opts, COMMENT_OPTIONS);
}
var popupTemplate = '\
<div class="sphinx-comments" id="sc<%id%>">\
<p class="sort-options">\
Sort by:\
<a href="#" class="sort-option byrating">best rated</a>\
<a href="#" class="sort-option byascage">newest</a>\
<a href="#" class="sort-option byage">oldest</a>\
</p>\
<div class="comment-header">Comments</div>\
<div class="comment-loading" id="cn<%id%>">\
loading comments... <img src="<%loadingImage%>" alt="" /></div>\
<ul id="cl<%id%>" class="comment-ul"></ul>\
<div id="ca<%id%>">\
<p class="add-a-comment">Add a comment\
(<a href="#" class="comment-markup" id="ab<%id%>">markup</a>):</p>\
<div class="comment-markup-box" id="mb<%id%>">\
reStructured text markup: <i>*emph*</i>, <b>**strong**</b>, \
<code>``code``</code>, \
code blocks: <code>::</code> and an indented block after blank line</div>\
<form method="post" id="cf<%id%>" class="comment-form" action="">\
<textarea name="comment" cols="80"></textarea>\
<p class="propose-button">\
<a href="#" id="pc<%id%>" class="show-propose-change">\
Propose a change &#9657;\
</a>\
<a href="#" id="hc<%id%>" class="hide-propose-change">\
Propose a change &#9663;\
</a>\
</p>\
<textarea name="proposal" id="pt<%id%>" cols="80"\
spellcheck="false"></textarea>\
<input type="submit" value="Add comment" />\
<input type="hidden" name="node" value="<%id%>" />\
<input type="hidden" name="parent" value="" />\
</form>\
</div>\
</div>';
var commentTemplate = '\
<div id="cd<%id%>" class="sphinx-comment<%css_class%>">\
<div class="vote">\
<div class="arrow">\
<a href="#" id="uv<%id%>" class="vote" title="vote up">\
<img src="<%upArrow%>" />\
</a>\
<a href="#" id="uu<%id%>" class="un vote" title="vote up">\
<img src="<%upArrowPressed%>" />\
</a>\
</div>\
<div class="arrow">\
<a href="#" id="dv<%id%>" class="vote" title="vote down">\
<img src="<%downArrow%>" id="da<%id%>" />\
</a>\
<a href="#" id="du<%id%>" class="un vote" title="vote down">\
<img src="<%downArrowPressed%>" />\
</a>\
</div>\
</div>\
<div class="comment-content">\
<p class="tagline comment">\
<span class="user-id"><%username%></span>\
<span class="rating"><%pretty_rating%></span>\
<span class="delta"><%time.delta%></span>\
</p>\
<div class="comment-text comment"><#text#></div>\
<p class="comment-opts comment">\
<a href="#" class="reply hidden" id="rl<%id%>">reply &#9657;</a>\
<a href="#" class="close-reply" id="cr<%id%>">reply &#9663;</a>\
<a href="#" id="sp<%id%>" class="show-proposal">proposal &#9657;</a>\
<a href="#" id="hp<%id%>" class="hide-proposal">proposal &#9663;</a>\
<a href="#" id="dc<%id%>" class="delete-comment hidden">delete</a>\
<span id="cm<%id%>" class="moderation hidden">\
<a href="#" id="ac<%id%>" class="accept-comment">accept</a>\
</span>\
</p>\
<pre class="proposal" id="pr<%id%>">\
<#proposal_diff#>\
</pre>\
<ul class="comment-children" id="cl<%id%>"></ul>\
</div>\
<div class="clearleft"></div>\
</div>\
</div>';
var replyTemplate = '\
<li>\
<div class="reply-div" id="rd<%id%>">\
<form id="rf<%id%>">\
<textarea name="comment" cols="80"></textarea>\
<input type="submit" value="Add reply" />\
<input type="button" value="Cancel" />\
<input type="hidden" name="parent" value="<%id%>" />\
<input type="hidden" name="node" value="" />\
</form>\
</div>\
</li>';
$(document).ready(function() {
init();
});
})(jQuery);
$(document).ready(function() {
// add comment anchors for all paragraphs that are commentable
$('.sphinx-has-comment').comment();
// highlight search words in search results
$("div.context").each(function() {
var params = $.getQueryParameters();
var terms = (params.q) ? params.q[0].split(/\s+/) : [];
var result = $(this);
$.each(terms, function() {
result.highlightText(this.toLowerCase(), 'highlighted');
});
});
// directly open comment window if requested
var anchor = document.location.hash;
if (anchor.substring(0, 9) == '#comment-') {
$('#ao' + anchor.substring(9)).click();
document.location.hash = '#s' + anchor.substring(9);
}
});

View File

@ -0,0 +1,676 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Définir et manipuler des classes &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Interactions avec lutilisateur" href="prompt.html" />
<link rel="prev" title="Sphinx et docutils" href="docutils.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="prompt.html" title="Interactions avec lutilisateur"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="docutils.html" title="Sphinx et docutils"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="definir-et-manipuler-des-classes">
<h1>Définir et manipuler des classes<a class="headerlink" href="#definir-et-manipuler-des-classes" title="Lien permanent vers ce titre"></a></h1>
<dl class="glossary docutils">
<dt id="term-objet">objet</dt>
<dd>Un object est une entité possédant un type, un état, et un comportement.
Un object correspondant généralement à une entité du monde réel, mais
cette entité peut être abstraite.
On parle aussi d”<strong>instance</strong>.</dd>
</dl>
<p><strong>état dun objet</strong> : ensemble de propriétés auxquelles sont associées des
valeurs.</p>
<p>Les variables de lobjet sont appelées des <strong>attributs</strong>.
le comportement dun <a class="reference internal" href="#term-objet"><span class="xref std std-term">objet</span></a> :</p>
<ul class="simple">
<li>des actions effectuées sur lobjet</li>
<li>des appels faits sur lobjet</li>
</ul>
<p>envois de messages à lobjet = appel de <strong>méthodes</strong></p>
<div class="section" id="programmation-objet-premiere-approche">
<h2>programmation objet (première approche)<a class="headerlink" href="#programmation-objet-premiere-approche" title="Lien permanent vers ce titre"></a></h2>
<ul class="simple">
<li>le type et le protocole dun objet sont définis par sa classe</li>
<li>une classe possède un ensemble dattributs et de méthodes</li>
</ul>
<div class="section" id="deux-relations-possibles">
<h3>deux relations possibles<a class="headerlink" href="#deux-relations-possibles" title="Lien permanent vers ce titre"></a></h3>
<dl class="glossary docutils">
<dt id="term-heritage">heritage</dt>
<dd>relation «&nbsp;est une espèce de &nbsp;» utilisée entre une classe et une autre classe</dd>
<dt id="term-instantiation">instantiation</dt>
<dd>relation «&nbsp;est une instance de &nbsp;» entre un objet et une classe</dd>
</dl>
<ul class="simple">
<li>est une instance de (objets par rapport à classe)</li>
<li>est une espèce de (classe par rapport à classe, <a class="reference internal" href="#term-heritage"><span class="xref std std-term">heritage</span></a>)</li>
</ul>
<p><strong>instance</strong></p>
<ul class="simple">
<li>définition dune classe</li>
<li>instance de classe : on peut créer des objets à partir dun type «&nbsp;classe&nbsp;»
(une classe est instanciable)</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">A</span><span class="p">()</span>
</pre></div>
</div>
<p><a class="reference internal" href="#term-heritage"><span class="xref std std-term">heritage</span></a> : notation en python</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="n">A</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">B</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">b</span><span class="p">)</span> <span class="o">==</span> <span class="n">B</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">A</span><span class="p">)</span> <span class="o">==</span> <span class="kc">True</span>
</pre></div>
</div>
<p>possibilité en python dhéritage multiple:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="n">B</span><span class="p">,</span> <span class="n">C</span><span class="p">):</span> <span class="k">pass</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="attribut-d-objets-et-de-classes">
<h2>attribut dobjets et de classes<a class="headerlink" href="#attribut-d-objets-et-de-classes" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span>
<span class="go">&lt;object object at 0x7f77c9cda0d0&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">a</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">vars</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">{&#39;a&#39;: 3}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;a&#39;: 3}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;__module__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="o">.</span><span class="n">c</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;c&#39;: 5, &#39;__module__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">c</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">z</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">z</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;a&#39;: 3, &#39;z&#39;: 3}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;c&#39;: 5, &#39;__module__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MaKlass</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">unefonction</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">x</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MaKlass</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;__module__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;unefonction&#39;: &lt;function unefonction at 0x7f77c5b0c488&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span> <span class="o">=</span> <span class="n">MaKlass</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">autrefonc</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
<span class="k">def</span> <span class="nf">autrefonc</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="o">^</span>
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">autrefonc</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">x</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span><span class="o">.</span><span class="n">autrefonc</span> <span class="o">=</span> <span class="n">autrefonc</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;autrefonc&#39;: &lt;function autrefonc at 0x7f77c5b0c500&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MaKlass</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;__module__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;unefonction&#39;: &lt;function unefonction at 0x7f77c5b0c488&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MaKlass</span><span class="o">.</span><span class="n">unefonction</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="s2">&quot;toto&quot;</span><span class="p">)</span>
<span class="go">toto</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span><span class="o">.</span><span class="n">unefonction</span><span class="p">(</span><span class="s2">&quot;toto&quot;</span><span class="p">)</span>
<span class="go">toto</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;autrefonc&#39;: &lt;function autrefonc at 0x7f77c5b0c500&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MaKlass</span><span class="o">.</span><span class="n">toto</span> <span class="o">=</span> <span class="s2">&quot;test&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{&#39;autrefonc&#39;: &lt;function autrefonc at 0x7f77c5b0c500&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">k</span><span class="o">.</span><span class="n">toto</span>
<span class="go">&#39;test&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="le-dict-avec-l-heritage-de-classe">
<h2>le __dict__ avec lhéritage de classe<a class="headerlink" href="#le-dict-avec-l-heritage-de-classe" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">A</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">dict_proxy({&#39;__dict__&#39;: &lt;attribute &#39;__dict__&#39; of &#39;A&#39; objects&gt;, &#39;__module__&#39;: &#39;__main__&#39;, &#39;__weakref__&#39;: &lt;attribute &#39;__weakref__&#39; of &#39;A&#39; objects&gt;, &#39;__doc__&#39;: None})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="n">A</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">b</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">c</span> <span class="o">=</span> <span class="mi">2</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="n">c</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="n">b</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="vm">__class__</span>
<span class="go">&lt;class &#39;__main__.C&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__dict__</span>
<span class="go">dict_proxy({&#39;__module__&#39;: &#39;__main__&#39;, &#39;c&#39;: 2, &#39;__doc__&#39;: None})</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="method-resolution-object">
<h2>method resolution object<a class="headerlink" href="#method-resolution-object" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">A</span><span class="o">.</span><span class="vm">__mro__</span>
<span class="go">(&lt;class &#39;__main__.A&#39;&gt;, &lt;type &#39;object&#39;&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="n">A</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">B</span><span class="o">.</span><span class="vm">__mro__</span>
<span class="go">(&lt;class &#39;__main__.B&#39;&gt;, &lt;class &#39;__main__.A&#39;&gt;, &lt;type &#39;object&#39;&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">A</span><span class="p">,</span> <span class="n">B</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">Error when calling the metaclass bases</span>
<span class="go"> Cannot create a consistent method resolution</span>
<span class="go">order (MRO) for bases A, B</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="section" id="introspection-contre-encapsulation">
<h3>introspection contre encapsulation<a class="headerlink" href="#introspection-contre-encapsulation" title="Lien permanent vers ce titre"></a></h3>
<p>voir un objet comme un espace de nommage. Cest plus <strong>agile</strong>.</p>
<p>attributs et méthodes vus comme des ajouts dans lespace de nommage</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">x</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">f</span> <span class="o">=</span> <span class="n">function</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">f</span><span class="p">(</span><span class="s2">&quot;hello&quot;</span><span class="p">)</span>
<span class="go">hello</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="la-necessite-d-un-design-objet">
<h3>la nécessité dun design objet<a class="headerlink" href="#la-necessite-d-un-design-objet" title="Lien permanent vers ce titre"></a></h3>
<p>affichage dune calculette, il faut créer un type <cite>Touche</cite>
qui contient deux désignations : <cite>Chiffre</cite> et <cite>operation</cite>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="nb">type</span> <span class="n">operation</span> <span class="o">=</span> <span class="n">Plus</span> <span class="o">|</span> <span class="n">Moins</span> <span class="o">|</span> <span class="n">Divise</span>
<span class="nb">type</span> <span class="n">touche</span> <span class="o">=</span> <span class="n">Chiffre</span> <span class="n">of</span> <span class="nb">int</span> <span class="o">|</span> <span class="n">Memoire</span> <span class="o">|</span> <span class="n">Op</span> <span class="n">of</span> <span class="n">operation</span>
</pre></div>
</div>
<p>soit, on définit un type touche, soit on ne définit pas ce type:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="nb">type</span> <span class="n">operation</span> <span class="o">=</span> <span class="n">Plus</span> <span class="o">|</span> <span class="n">Moins</span> <span class="o">|</span> <span class="n">Divise</span>
<span class="nb">type</span> <span class="n">memoire</span> <span class="o">=</span> <span class="n">Memoire</span>
<span class="nb">type</span> <span class="n">chiffre</span> <span class="o">=</span> <span class="n">Chiffre</span>
</pre></div>
</div>
<ul class="simple">
<li>les structures de données (int, str, list, dict…) : types de base</li>
<li>les structures de données utilisateur : les classes !</li>
</ul>
<dl class="function">
<dt id="type">
<code class="descname">type</code><span class="sig-paren">(</span><em>objname</em><span class="sig-paren">)</span><a class="headerlink" href="#type" title="Lien permanent vers cette définition"></a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Paramètres:</th><td class="field-body"><strong>objname</strong> lobjet dont on veut connaître le type</td>
</tr>
</tbody>
</table>
</dd></dl>
</div>
</div>
<div class="section" id="manipulations-sur-les-classes-et-les-objets">
<h2>Manipulations sur les classes et les objets<a class="headerlink" href="#manipulations-sur-les-classes-et-les-objets" title="Lien permanent vers ce titre"></a></h2>
<p>En python un type et une classe cest la même chose. Une classe
est un type standard. En python tout est objet, et tout provient dun seul objet
(qui sappelle <code class="docutils literal"><span class="pre">object</span></code>).</p>
<ul class="simple">
<li>encapsulation (cacher les attributs (variables détat)) dun objet.</li>
<li>interfaces : chaque aspect dune classe peut être vu comme une interface.</li>
</ul>
<p>Une interface décrit un ensemble de comportements.
on peut considérer une interface comme un protocole dutilisation dun objet
dans un contexte donné.</p>
<p>on peut alors créer des outils qui sauront traiter nimporte quel objet
pourvu quil respecte une ensemble dinterfaces.</p>
<div class="admonition-todo admonition" id="index-0">
<p class="first admonition-title">À faire</p>
<p class="last">travailler lhéritage, laggrégation, la délégation</p>
</div>
<p>Voici un exemple de classe <cite>Voiture</cite> :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Voiture</span><span class="p">(</span><span class="n">Prix</span><span class="p">,</span> <span class="n">Turbo</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">constructeur</span><span class="p">,</span> <span class="n">vitesse_max</span><span class="o">=</span><span class="mi">160</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constructeur</span> <span class="o">=</span> <span class="n">constructeur</span>
<span class="bp">self</span><span class="o">.</span><span class="n">vitesse_max</span> <span class="o">=</span> <span class="n">vitesse_max</span>
<span class="k">def</span> <span class="nf">roule</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;vroummm&quot;</span>
<span class="k">def</span> <span class="nf">signaletique</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;constructeur : </span><span class="si">{0}</span><span class="s2">, vitesse_max </span><span class="si">{1}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">constructeur</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">vitesse_max</span><span class="p">)</span>
</pre></div>
</div>
<p>jinstancie ma classe <cite>Voiture</cite> :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ma_voiture</span> <span class="o">=</span> <span class="n">Voiture</span><span class="p">(</span><span class="s2">&quot;ma_marque&quot;</span><span class="p">,</span> <span class="s2">&quot;150km/h&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ma_voiture</span><span class="o">.</span><span class="n">roule</span><span class="p">()</span>
<span class="go">&#39;vroummm&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ma_voiture</span><span class="o">.</span><span class="n">signaletique</span><span class="p">()</span>
<span class="go">&#39;constructeur : ma_marque, vitesse_max 150km/h&#39;</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-1">
<p class="first admonition-title">À faire</p>
<p class="last">faire des traitements dans linit</p>
</div>
<ul class="simple">
<li>héritage (est une sorte de)</li>
<li>polymorphisme : un objet apparait comme une instance dune classe parente</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Turbo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">turbo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;VRRRRROUUUMMM&quot;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="n">DoDoche</span><span class="p">(</span><span class="s2">&quot;marque&quot;</span><span class="p">,</span> <span class="mi">160</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="o">.</span><span class="n">get_prix</span><span class="p">()</span>
<span class="go">&#39;7000&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">Prix</span><span class="p">)</span>
<span class="go">True</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>mais lobjet conserve son identité :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="go">&lt;type &#39;Voiture&#39;&gt;</span>
</pre></div>
</div>
<p>la fonction <code class="docutils literal"><span class="pre">achete_voiture()</span></code> sera appelée indépendamment du type de lobjet,
du moment que lobjet a une méthode <cite>get_prix()</cite>, cest le duck typing, quil
est préférable de ramener au polymorphisme dobjet, ou bien utiliser les <a class="reference internal" href="stdlib.html#module-abc" title="abc: les abstract base classes"><code class="xref py py-mod docutils literal"><span class="pre">abc</span></code></a>
(abstract base classes).</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">achete_voiture</span><span class="p">(</span><span class="n">voiture</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">voiture</span><span class="p">,</span> <span class="s2">&quot;get_prix&quot;</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;pas le bon type&quot;</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">&quot;prix de la voiture: </span><span class="si">{0}</span><span class="s2"> euros&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">voiture</span><span class="o">.</span><span class="n">get_prix</span><span class="p">())</span>
</pre></div>
</div>
<p>tout le code :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Turbo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">turbo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;VRRRRROUUUMMM&quot;</span>
<span class="k">class</span> <span class="nc">Prix</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">get_prix</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">NotImplementedError</span>
<span class="k">class</span> <span class="nc">Voiture</span><span class="p">(</span><span class="n">Prix</span><span class="p">,</span> <span class="n">Turbo</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">constructeur</span><span class="p">,</span> <span class="n">vitesse_max</span><span class="o">=</span><span class="mi">160</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">constructeur</span> <span class="o">=</span> <span class="n">constructeur</span>
<span class="bp">self</span><span class="o">.</span><span class="n">vitesse_max</span> <span class="o">=</span> <span class="n">vitesse_max</span>
<span class="k">def</span> <span class="nf">roule</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;vroummm&quot;</span>
<span class="k">def</span> <span class="nf">signaletique</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;constructeur : </span><span class="si">{0}</span><span class="s2">, vitesse_max </span><span class="si">{1}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">constructeur</span><span class="p">,</span>
<span class="bp">self</span><span class="o">.</span><span class="n">vitesse_max</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">DoDoche</span><span class="p">(</span><span class="n">Voiture</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">get_prix</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;4000&quot;</span>
<span class="k">def</span> <span class="nf">achete_voiture</span><span class="p">(</span><span class="n">voiture</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">voiture</span><span class="p">,</span> <span class="s2">&quot;get_prix&quot;</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;pas le bon type&quot;</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">&quot;prix de la voiture: </span><span class="si">{0}</span><span class="s2"> euros&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">voiture</span><span class="o">.</span><span class="n">get_prix</span><span class="p">())</span>
</pre></div>
</div>
<p><a class="reference download internal" href="_downloads/heritage.py" download=""><code class="xref download docutils literal"><span class="pre">télécharger</span> <span class="pre">le</span> <span class="pre">code</span></code></a></p>
<ul class="simple">
<li><strong>laggrégation</strong></li>
</ul>
<p>un attribut est lui-même un objet (ce qui est fréquent en python)…</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">B</span><span class="p">:</span>
<span class="k">pass</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">A</span><span class="p">()</span>
<span class="n">a</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">B</span><span class="p">()</span>
</pre></div>
</div>
<ul class="simple">
<li><strong>la délégation</strong></li>
</ul>
<p>la fonction «&nbsp;property&nbsp;» est un élément du design de python lui-même</p>
<dl class="function">
<dt id="property">
<code class="descname">property</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#property" title="Lien permanent vers cette définition"></a></dt>
<dd></dd></dl>
</div>
<div class="section" id="les-patrons-de-conception">
<h2>les patrons de conception<a class="headerlink" href="#les-patrons-de-conception" title="Lien permanent vers ce titre"></a></h2>
<ul class="simple">
<li>le patron <strong>factory</strong></li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">NotFoundError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">MaClasse</span><span class="p">:</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">MaClasseDeux</span><span class="p">:</span>
<span class="k">pass</span>
<span class="n">binding</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">un</span><span class="o">=</span><span class="n">MaClasse</span><span class="p">,</span> <span class="n">deux</span><span class="o">=</span><span class="n">MaClasseDeux</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">ma_factory</span><span class="p">(</span><span class="n">key</span><span class="p">):</span>
<span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">binding</span><span class="p">:</span>
<span class="k">return</span> <span class="n">binding</span><span class="p">[</span><span class="n">key</span><span class="p">]()</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">NotFoundError</span><span class="p">(</span><span class="s2">&quot;keskece?&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference download internal" href="_downloads/patrons.py" download=""><code class="xref download docutils literal"><span class="pre">télécharger</span> <span class="pre">usine</span> <span class="pre">(factory)</span></code></a></p>
<ul class="simple">
<li>le patron <strong>wrapper</strong></li>
</ul>
<p><a class="reference download internal" href="_downloads/wrap.py" download=""><code class="xref download docutils literal"><span class="pre">télécharger</span> <span class="pre">wrapper</span></code></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Wrap</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">wrap</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">slots</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;_name&#39;</span><span class="p">,</span> <span class="s1">&#39;_w&#39;</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_name</span> <span class="o">=</span> <span class="n">name</span> <span class="ow">or</span> <span class="s2">&quot;wrapped_element&quot;</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_w</span> <span class="o">=</span> <span class="n">wrap</span>
<span class="k">def</span> <span class="nf">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
<span class="k">if</span> <span class="n">name</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">slots</span><span class="p">:</span>
<span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_w</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
<span class="c1"># def get_w(self, name):</span>
<span class="c1"># return getattr(self._w, name)</span>
<span class="c1"># def set_w(self, name, value):</span>
<span class="c1"># return setattr(self._w, name, value)</span>
<span class="c1"># _w = property (get_w, set_w)</span>
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;[W_Element </span><span class="si">%s</span><span class="s2">]&quot;</span><span class="o">%</span> <span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_name</span><span class="p">)</span>
</pre></div>
</div>
<p>exemple dutilisation de <cite>Wrap()</cite></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">O</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="o">=</span> <span class="n">O</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="s2">&quot;blah&quot;</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">wrap</span> <span class="k">import</span> <span class="n">Wrap</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span> <span class="o">=</span> <span class="n">Wrap</span><span class="p">(</span><span class="s2">&quot;monwrap&quot;</span><span class="p">,</span> <span class="n">o</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span><span class="o">.</span><span class="n">_name</span>
<span class="go">&#39;monwrap&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span><span class="o">.</span><span class="n">_w</span>
<span class="go">&lt;__main__.O instance at 0x7fbf177aaa28&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span><span class="o">.</span><span class="n">_w</span><span class="o">.</span><span class="n">a</span>
<span class="go">&#39;blah&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span><span class="o">.</span><span class="n">a</span>
<span class="go">&#39;blah&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span><span class="o">.</span><span class="n">u</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
File <span class="nb">&quot;wrap.py&quot;</span>, line <span class="m">11</span>, in <span class="n">__getattr__</span>
<span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_w</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
<span class="gr">AttributeError</span>: <span class="n">O instance has no attribute &#39;u&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>le patron de conception <strong>itérable</strong></li>
</ul>
<p><a class="reference download internal" href="_downloads/iterable.py" download=""><code class="xref download docutils literal"><span class="pre">télécharger</span> <span class="pre">iterable</span></code></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">liste</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;blah&#39;</span><span class="p">,</span> <span class="s1">&#39;blih&#39;</span><span class="p">,</span> <span class="s1">&#39;bluh&#39;</span><span class="p">]</span>
<span class="n">iterateur</span> <span class="o">=</span> <span class="n">liste</span><span class="o">.</span><span class="fm">__iter__</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">iterateur</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">iterateur</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">iterateur</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">iterateur</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="c1">#Traceback (most recent call last):</span>
<span class="c1"># File &#39;&lt;stdin&gt;&#39;, line 1, in &lt;module&gt;;</span>
<span class="c1">#StopIteration</span>
<span class="k">class</span> <span class="nc">Iterateur</span><span class="p">:</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">&lt;=</span> <span class="mi">10</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">StopIteration</span>
<span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">return</span> <span class="mi">2</span><span class="o">**</span><span class="bp">self</span><span class="o">.</span><span class="n">i</span>
<span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span>
<span class="n">iterateur</span> <span class="o">=</span> <span class="n">Iterateur</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">iterateur</span><span class="p">:</span> <span class="nb">print</span> <span class="n">i</span>
</pre></div>
</div>
<ul class="simple">
<li>le patron <strong>decorateur</strong></li>
</ul>
<p><a class="reference download internal" href="_downloads/decorateur.py" download=""><code class="xref download docutils literal"><span class="pre">télécharger</span> <span class="pre">decorateur</span></code></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">helloworld</span><span class="p">(</span><span class="n">ob</span><span class="p">):</span>
<span class="nb">print</span> <span class="s2">&quot;Hello world&quot;</span>
<span class="k">return</span> <span class="n">ob</span>
<span class="nd">@helloworld</span>
<span class="k">def</span> <span class="nf">myfunc</span><span class="p">():</span>
<span class="nb">print</span> <span class="s2">&quot;my function&quot;</span>
<span class="n">myfunc</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">myfunc</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">deco</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">func</span><span class="o">.</span><span class="n">attr</span> <span class="o">=</span> <span class="s1">&#39;decorated&#39;</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">func</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nd">@deco</span>
<span class="gp">... </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">attr</span>
<span class="go">&#39;decorated&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>autre exemple : les méthodes statiques</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="nd">@staticmethod</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">my_class_method</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
<span class="gp">... </span> <span class="c1"># do stuff here</span>
</pre></div>
</div>
</div>
<div class="section" id="metaclasses">
<h2>métaclasses<a class="headerlink" href="#metaclasses" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
<span class="go">&lt;type &#39;classobj&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">B</span><span class="p">)</span>
<span class="go">&lt;type &#39;type&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="nb">type</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="s1">&#39;C&#39;</span><span class="p">,</span> <span class="p">(),</span> <span class="p">{})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span>
<span class="go">&lt;class &#39;__main__.C&#39;&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">object</span><span class="p">)</span>
<span class="go">&lt;type &#39;type&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">type</span><span class="p">)</span>
<span class="go">&lt;type &#39;type&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="nb">type</span><span class="p">,</span> <span class="nb">object</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="nb">type</span><span class="p">)</span>
<span class="go">True</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MaMetaClasse</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Exemple d&#39;une métaclasse.&quot;&quot;&quot;</span>
<span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="n">metacls</span><span class="p">,</span> <span class="n">nom</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Création de notre classe.&quot;&quot;&quot;</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;On crée la classe </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">nom</span><span class="p">))</span>
<span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="n">metacls</span><span class="p">,</span> <span class="n">nom</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="nb">dict</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">MaClasse</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">MaMetaClasse</span>
</pre></div>
</div>
<p>exemple : forcer limplémentation dun singleton avec les métaclasses</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Singleton</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
<span class="n">instance</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="bp">cls</span><span class="o">.</span><span class="n">instance</span><span class="p">:</span>
<span class="bp">cls</span><span class="o">.</span><span class="n">instance</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">Singleton</span><span class="p">,</span> <span class="bp">cls</span><span class="p">)</span><span class="o">.</span><span class="fm">__call__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">)</span>
<span class="k">return</span> <span class="bp">cls</span><span class="o">.</span><span class="n">instance</span>
<span class="k">class</span> <span class="nc">ASingleton</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">Singleton</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">ASingleton</span><span class="p">()</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">ASingleton</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">a</span> <span class="ow">is</span> <span class="n">b</span>
<span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">b</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">BSingleton</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">Singleton</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">BSingleton</span><span class="p">()</span>
<span class="n">d</span> <span class="o">=</span> <span class="n">BSingleton</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">c</span> <span class="ow">is</span> <span class="n">d</span>
<span class="nb">print</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">)</span>
<span class="k">assert</span> <span class="n">c</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">a</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="prompt.html" title="Interactions avec lutilisateur"
>suivant</a> |</li>
<li class="right" >
<a href="docutils.html" title="Sphinx et docutils"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,135 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sphinx et docutils &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Définir et manipuler des classes" href="classes.html" />
<link rel="prev" title="Tests unitaires et pile dappels" href="testsunitaires.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="classes.html" title="Définir et manipuler des classes"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="testsunitaires.html" title="Tests unitaires et pile dappels"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="sphinx-et-docutils">
<h1>Sphinx et docutils<a class="headerlink" href="#sphinx-et-docutils" title="Lien permanent vers ce titre"></a></h1>
<div class="section" id="docutils">
<h2>Docutils<a class="headerlink" href="#docutils" title="Lien permanent vers ce titre"></a></h2>
<p>Il y a des librairies de bas niveau qui permettent de générer de lodt, je pense à pyUNO, ou bien <a class="reference external" href="https://pythonhosted.org/ezodf/">ezodf</a></p>
<p>A lopposé, il y a des librairies de très haut niveau intégré à des chaînes de documentation avec des sources en xml, des modèles documentaires, des chartes graphiques, etc. Par exemple, <a class="reference external" href="http://scenari-platform.org/projects/scenari/fr/pres/co/">scenari</a></p>
<p>Un juste milieu est la très intéressante librairie <a class="reference external" href="http://docutils.sourceforge.net/">docutils</a> :</p>
<p>Il sagit dune libairie python très utilisée dans le monde python (par exemple, la documentation officielle python est rédigée en <a class="reference external" href="http://docutils.sourceforge.net/docs/index.html">syntaxe docutils</a>).</p>
<p>Cest une <a class="reference external" href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">syntaxe wiki</a> assez puissante, un sur-ensemble de la très connue syntaxe markdown.</p>
<p>Pour linstaller:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">apt</span><span class="o">-</span><span class="n">get</span> <span class="n">install</span> <span class="n">python</span><span class="o">-</span><span class="n">docutils</span>
</pre></div>
</div>
<p>Il y a plusieurs utilitaires : <code class="docutils literal"><span class="pre">rst2html</span></code>, <code class="docutils literal"><span class="pre">rst2*</span></code>, lutilitaire que je te conseille est : <code class="docutils literal"><span class="pre">rst2odt</span></code>.</p>
<p>Pour lusage de <a class="reference external" href="http://docutils.sourceforge.net/docs/user/odt.html">rst2odt</a> cest simple, on part dun fichier texte formaté en restructured text:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">rst2odt</span> <span class="n">fichier</span><span class="o">.</span><span class="n">txt</span> <span class="o">&gt;</span> <span class="n">fichier</span><span class="o">.</span><span class="n">odt</span>
</pre></div>
</div>
<p>Et voilà simple, pratique, efficace.</p>
<p>Cest loutil que nous utilisons en priorité. Voici un exemple dusage avancé avec lutilisation dun modèle:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">rst2odt</span> <span class="o">--</span><span class="n">create</span><span class="o">-</span><span class="n">links</span> <span class="o">--</span><span class="n">file</span><span class="o">-</span><span class="n">insertion</span><span class="o">-</span><span class="n">enabled</span> <span class="o">--</span><span class="n">raw</span><span class="o">-</span><span class="n">enabled</span> <span class="o">--</span><span class="n">endnotes</span><span class="o">-</span><span class="n">end</span><span class="o">-</span><span class="n">doc</span> \
<span class="o">--</span><span class="n">stylesheet</span><span class="o">=</span><span class="n">styles</span><span class="o">/</span><span class="n">styles</span><span class="o">.</span><span class="n">odt</span> <span class="o">--</span><span class="n">custom</span><span class="o">-</span><span class="n">odt</span><span class="o">-</span><span class="n">footer</span><span class="o">=</span><span class="s2">&quot;XXXREMPLACEHEADERXXX&quot;</span> \
<span class="n">DossierCommercial</span><span class="o">.</span><span class="n">rst</span> <span class="o">&gt;</span> <span class="n">DossierCommercial</span><span class="o">.</span><span class="n">odt</span>
</pre></div>
</div>
</div>
<div class="section" id="la-documentation-technique">
<h2>La documentation technique<a class="headerlink" href="#la-documentation-technique" title="Lien permanent vers ce titre"></a></h2>
<p>Loutil <a class="reference external" href="http://sphinx-doc.org/">sphinx</a></p>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="classes.html" title="Définir et manipuler des classes"
>suivant</a> |</li>
<li class="right" >
<a href="testsunitaires.html" title="Tests unitaires et pile dappels"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,343 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Le style de programmation par exceptions &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Les design patterns" href="DesignPatterns.html" />
<link rel="prev" title="Programmation python courante" href="specialmethods.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="DesignPatterns.html" title="Les design patterns"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="specialmethods.html" title="Programmation python courante"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="le-style-de-programmation-par-exceptions">
<h1>Le style de programmation par exceptions<a class="headerlink" href="#le-style-de-programmation-par-exceptions" title="Lien permanent vers ce titre"></a></h1>
<dl class="glossary docutils">
<dt id="term-exception">Exception</dt>
<dd>Les exceptions permettent de récupérer des situations où le calcul ne peut pas se poursuivre.
Dans ces cas, un récupérateur dexceptions permet de continuer le calcul
sachant quune des branches a échoué.</dd>
</dl>
<p>Exemple d”<a class="reference internal" href="#term-exception"><span class="xref std std-term">exception</span></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">1</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">AssertionError</span>
</pre></div>
</div>
<div class="section" id="la-regle-du-samourai">
<h2>La règle du samouraï<a class="headerlink" href="#la-regle-du-samourai" title="Lien permanent vers ce titre"></a></h2>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">règle du Samouraï : une fonction doit renvoyer le résultat escompté
ou bien lever une exception</p>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function_raise</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">type</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">==</span> <span class="nb">int</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;Pas le bon type&quot;</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">e</span> <span class="o">=</span> <span class="n">function_raise</span><span class="p">(</span><span class="s2">&quot;une string&quot;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">e</span>
<span class="gp">...</span>
<span class="go">Pas le bon type</span>
<span class="go">&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>la fonction doit renvoyer des valeurs du même type (ou bien <code class="docutils literal"><span class="pre">None</span></code>)</li>
<li>la fonction doit lever une exception appropriée</li>
</ul>
</div>
<div class="section" id="utiliser-la-pile-d-appel-pour-debugger">
<h2>utiliser la pile dappel pour débugger<a class="headerlink" href="#utiliser-la-pile-d-appel-pour-debugger" title="Lien permanent vers ce titre"></a></h2>
<p>Utiliser la pile dappels, elle se lit de bas en haut. Il est possible de
provoquer cette pile dappels.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">traceback</span>
<span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-0">
<p class="first admonition-title">À faire</p>
<p class="last">sexercer à lire une pile dappels un peu complexe.</p>
</div>
<p>Traiter une exception avec</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">except</span><span class="p">:</span>
<span class="kn">import</span> <span class="nn">traceback</span>
<span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">bla</span> <span class="n">bla</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">bla</span> <span class="n">bla</span>
</pre></div>
</div>
<div class="admonition attention">
<p class="first admonition-title">Attention</p>
<p class="last">ne <strong>jamais</strong> briser la pile dappels sans savoir précisément
ce que lon fait, et remonter une autre exception</p>
</div>
<p>Exemple :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s2">&quot;pas le bon type&quot;</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="s2">&quot;ok&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function2</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s2">&quot;c&#39;est &quot;</span> <span class="o">+</span> <span class="n">function</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="s2">&quot;on a une autre exception là&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">function2</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">e</span>
<span class="gp">...</span>
<span class="go">on a une autre exception là</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Le raise (ou le re-raise) est souvent utilisé pour lever une exception métier
et cacher une exception système de bas niveau.</p>
<p>exemple:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="n">add_s</span><span class="p">(</span><span class="n">dn</span><span class="p">,</span> <span class="n">listdata</span><span class="p">)</span>
<span class="k">except</span> <span class="n">ldap</span><span class="o">.</span><span class="n">LDAPError</span><span class="p">,</span> <span class="n">err</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">MyOwnError</span><span class="p">(</span><span class="n">msg</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">err</span><span class="p">))</span>
<span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
<span class="k">pass</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-1">
<p class="first admonition-title">À faire</p>
<p class="last">dans quel cas entrons-nous dans le <code class="docutils literal"><span class="pre">else</span></code> ? dans le <code class="docutils literal"><span class="pre">finally</span></code> ?</p>
</div>
<div class="admonition-todo admonition" id="index-2">
<p class="first admonition-title">À faire</p>
<p class="last">créer des exceptions métier</p>
</div>
<p>exemple dexceptions <em>dans la vraie vie</em>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="s2">&quot;user defined exceptions&quot;</span>
<span class="c1"># Exceptions for an Option</span>
<span class="k">class</span> <span class="nc">PropertiesOptionError</span><span class="p">(</span><span class="ne">AttributeError</span><span class="p">):</span>
<span class="s2">&quot;attempt to access to an option with a property that is not allowed&quot;</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">proptype</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">proptype</span> <span class="o">=</span> <span class="n">proptype</span>
<span class="nb">super</span><span class="p">(</span><span class="n">PropertiesOptionError</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="c1">#____________________________________________________________</span>
<span class="c1"># Exceptions for a Config</span>
<span class="k">class</span> <span class="nc">ConfigError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;attempt to change an option&#39;s owner without a value</span>
<span class="sd"> or in case of `_cfgimpl_descr` is None</span>
<span class="sd"> or if a calculation cannot be carried out&quot;&quot;&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">ContextError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;context needed but not given</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">ConflictError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="s2">&quot;duplicate options are present in a single config&quot;</span>
<span class="k">pass</span>
<span class="c1">#____________________________________________________________</span>
<span class="c1"># miscellaneous exceptions</span>
<span class="k">class</span> <span class="nc">RequirementError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;a recursive loop occurs in the requirements tree</span>
<span class="sd"> requires</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">SlaveError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="s2">&quot;problem with a slave&#39;s value length&quot;</span>
<span class="k">pass</span>
<span class="k">class</span> <span class="nc">ConstError</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">):</span>
<span class="s2">&quot;no uniq value in _NameSpace&quot;</span>
<span class="k">pass</span>
</pre></div>
</div>
<p>Créer le plus possible ses propres exceptions spécifiques au programme
La programmation par exception peut vite devenir un style de programmation
très utilisé. Cest assez agréable mais le réserver pour la gestion dune situation
particulière, que ça reste une intervention pour les cas non gérés par le programme
(en général).</p>
</div>
<div class="section" id="les-exceptions-imbriquees">
<h2>Les exceptions imbriquées<a class="headerlink" href="#les-exceptions-imbriquees" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">ma_func</span><span class="p">()</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">do_something</span><span class="p">()</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">do_somethin_else</span><span class="p">()</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>Exemple de programme utilisant massivement la programmation par exceptions :
<a class="reference external" href="http://tiramisu.labs.libre-entreprise.org/">tiramisu</a></p>
</div>
<div class="section" id="la-hierarchie-des-exceptions">
<h2>La hiérarchie des exceptions<a class="headerlink" href="#la-hierarchie-des-exceptions" title="Lien permanent vers ce titre"></a></h2>
<p>Extrait de la documentation officielle:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="ne">BaseException</span>
<span class="o">+--</span> <span class="ne">SystemExit</span>
<span class="o">+--</span> <span class="ne">KeyboardInterrupt</span>
<span class="o">+--</span> <span class="ne">GeneratorExit</span>
<span class="o">+--</span> <span class="ne">Exception</span>
<span class="o">+--</span> <span class="ne">StopIteration</span>
<span class="o">+--</span> <span class="n">StandardError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">BufferError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ArithmeticError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">FloatingPointError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">OverflowError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">ZeroDivisionError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">AssertionError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">AttributeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">EnvironmentError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">IOError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">OSError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">WindowsError</span> <span class="p">(</span><span class="n">Windows</span><span class="p">)</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">VMSError</span> <span class="p">(</span><span class="n">VMS</span><span class="p">)</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">EOFError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ImportError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">LookupError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">IndexError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">KeyError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">MemoryError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">NameError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">UnboundLocalError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ReferenceError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">RuntimeError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">NotImplementedError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">SyntaxError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">IndentationError</span>
<span class="o">|</span> <span class="o">|</span> <span class="o">+--</span> <span class="ne">TabError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">SystemError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">TypeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">ValueError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeDecodeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeEncodeError</span>
<span class="o">|</span> <span class="o">+--</span> <span class="ne">UnicodeTranslateError</span>
<span class="o">+--</span> <span class="ne">Warning</span>
<span class="o">+--</span> <span class="ne">DeprecationWarning</span>
<span class="o">+--</span> <span class="ne">PendingDeprecationWarning</span>
<span class="o">+--</span> <span class="ne">RuntimeWarning</span>
<span class="o">+--</span> <span class="ne">SyntaxWarning</span>
<span class="o">+--</span> <span class="ne">UserWarning</span>
<span class="o">+--</span> <span class="ne">FutureWarning</span>
<span class="o">+--</span> <span class="ne">ImportWarning</span>
<span class="o">+--</span> <span class="ne">UnicodeWarning</span>
<span class="o">+--</span> <span class="ne">BytesWarning</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="DesignPatterns.html" title="Les design patterns"
>suivant</a> |</li>
<li class="right" >
<a href="specialmethods.html" title="Programmation python courante"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,199 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Liste des exercices &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="prev" title="La librairie standard" href="stdlib.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="stdlib.html" title="La librairie standard"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="liste-des-exercices">
<h1>Liste des exercices<a class="headerlink" href="#liste-des-exercices" title="Lien permanent vers ce titre"></a></h1>
<p>Voici la liste des liens vers les différents exercices de la formation.</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">travailler lhéritage, laggrégation, la délégation</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="classes.html#index-0"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/classes.txt, à la ligne 250)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">faire des traitements dans linit</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="classes.html#index-1"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/classes.txt, à la ligne 265)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">sexercer à lire une pile dappels un peu complexe.</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="exceptions.html#index-0"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/exceptions.txt, à la ligne 60)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">dans quel cas entrons-nous dans le <code class="docutils literal"><span class="pre">else</span></code> ? dans le <code class="docutils literal"><span class="pre">finally</span></code> ?</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="exceptions.html#index-1"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/exceptions.txt, à la ligne 114)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">créer des exceptions métier</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="exceptions.html#index-2"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/exceptions.txt, à la ligne 116)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">faire un petit projet dinterpréteur ligne de commande du jeu C+/C-</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="prompt.html#index-0"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/prompt.txt, à la ligne 92)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last"><code class="docutils literal"><span class="pre">print</span> <span class="pre">1</span></code> et <code class="docutils literal"><span class="pre">print</span> <span class="pre">&quot;1&quot;</span></code> renvoient le même résultat. Pourquoi ?</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="structures.html#index-0"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/structures.txt, à la ligne 205)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">écrire un test unitaire avec <cite>py.test</cite> pour la fonction suivante</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="testsunitaires.html#index-0"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/testsunitaires.txt, à la ligne 42)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">créer une variable</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-0"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 14)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">jouer avec les types</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-1"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 47)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">lower(), upper(), strip(), title()</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-2"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 102)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">addition de listes, append, tranches, tri de listes</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-3"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 342)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">defaultdict, get (avec une valeur par défaut)</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-4"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 353)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">linterpréteur python pour lintrospection des objets</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-5"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 386)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">coercion, typage dynamique, inférence de type</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-6"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 617)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">en python un type et une classe, cest la même chose</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-7"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 644)</p>
<div class="admonition-todo admonition">
<p class="first admonition-title">À faire</p>
<p class="last">«&nbsp;duck typing&nbsp;» en python</p>
</div>
<p class="todo-source">(l'<a class="reference internal" href="type.html#index-8"><em>entrée originale</em></a> se trouve dans /media/gwen/169254b3-cf68-41d0-a170-baa25153030a/coffre/entrepot/depot/lab71.info/wcrepositories/pyfundoc/fr/type.txt, à la ligne 646)</p>
</div>
<div class="section" id="exercices-a-faire">
<h1>exercices à faire<a class="headerlink" href="#exercices-a-faire" title="Lien permanent vers ce titre"></a></h1>
<ul class="simple">
<li>implémenter un script qui lit les arguments de la ligne de commande et qui les écrit sur la sortie standard</li>
<li>implémenter les sous-classes de shape point et cercle, calculer le périmètre.</li>
<li>itérer sur une liste et récupérer la valeur maximum de cette liste (la fonction builtin <em>max</em>)</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">9</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">4</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">max</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">9</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="stdlib.html" title="La librairie standard"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,332 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Index &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="#" />
<link rel="search" title="Recherche" href="search.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="#" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<h1 id="index">Index</h1>
<div class="genindex-jumpbox">
<a href="#_"><strong>_</strong></a>
| <a href="#A"><strong>A</strong></a>
| <a href="#B"><strong>B</strong></a>
| <a href="#C"><strong>C</strong></a>
| <a href="#D"><strong>D</strong></a>
| <a href="#E"><strong>E</strong></a>
| <a href="#G"><strong>G</strong></a>
| <a href="#H"><strong>H</strong></a>
| <a href="#I"><strong>I</strong></a>
| <a href="#L"><strong>L</strong></a>
| <a href="#O"><strong>O</strong></a>
| <a href="#P"><strong>P</strong></a>
| <a href="#R"><strong>R</strong></a>
| <a href="#S"><strong>S</strong></a>
| <a href="#T"><strong>T</strong></a>
| <a href="#U"><strong>U</strong></a>
| <a href="#V"><strong>V</strong></a>
| <a href="#Y"><strong>Y</strong></a>
</div>
<h2 id="_">_</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="specialmethods.html#__add__">__add__() (fonction de base)</a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="specialmethods.html#__init__">__init__() (fonction de base)</a>
</li>
</ul></td>
</tr></table>
<h2 id="A">A</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-abc">abc (module)</a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#abc.abc.register">abc.register() (dans le module abc)</a>
</li>
</ul></td>
</tr></table>
<h2 id="B">B</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-builtins">builtins (module)</a>
</li>
</ul></td>
</tr></table>
<h2 id="C">C</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="prompt.html#module-cmd">cmd (module)</a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="type.html#module-collections">collections (module)</a>
</li>
</ul></td>
</tr></table>
<h2 id="D">D</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-doctest">doctest (module)</a>
</li>
</ul></td>
</tr></table>
<h2 id="E">E</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="exceptions.html#term-exception"><strong>Exception</strong></a>
</li>
</ul></td>
</tr></table>
<h2 id="G">G</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-getpass">getpass (module)</a>
</li>
</ul></td>
</tr></table>
<h2 id="H">H</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="classes.html#term-heritage"><strong>heritage</strong></a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-hotshot">hotshot (module)</a>
</li>
</ul></td>
</tr></table>
<h2 id="I">I</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="settings.html#term-idle"><strong>IDLE</strong></a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="classes.html#term-instantiation"><strong>instantiation</strong></a>
</li>
<li><a href="stdlib.html#module-IPy">IPy (module)</a>
</li>
</ul></td>
</tr></table>
<h2 id="L">L</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="settings.html#term-librairie-standard"><strong>librairie standard</strong></a>
</li>
</ul></td>
</tr></table>
<h2 id="O">O</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="classes.html#term-objet"><strong>objet</strong></a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-optparse">optparse (module)</a>
</li>
</ul></td>
</tr></table>
<h2 id="P">P</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="testsunitaires.html#module-pdb">pdb (module)</a>
</li>
<li><a href="classes.html#property">property() (fonction de base)</a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="testsunitaires.html#module-py.test">py.test (module)</a>
</li>
<li><a href="getting-started.html#term-python"><strong>python</strong></a>
</li>
<li><a href="specialmethods.html#index-0">PYTHONPATH</a>, <a href="specialmethods.html#index-1">[1]</a>, <a href="stdlib.html#index-0">[2]</a>
</li>
</ul></td>
</tr></table>
<h2 id="R">R</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="type.html#module-regexp">regexp (module)</a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="structures.html#term-return"><strong>return</strong></a>
</li>
</ul></td>
</tr></table>
<h2 id="S">S</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-shelve">shelve (module)</a>
</li>
<li><a href="getting-started.html#term-sphinx"><strong>sphinx</strong></a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-subprocess">subprocess (module)</a>
</li>
<li><a href="stdlib.html#module-sys">sys (module)</a>
</li>
<li><a href="stdlib.html#sys.sys.exit">sys.exit() (dans le module sys)</a>
</li>
</ul></td>
</tr></table>
<h2 id="T">T</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-time">time (module)</a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="classes.html#type">type() (fonction de base)</a>
</li>
</ul></td>
</tr></table>
<h2 id="U">U</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-unittest">unittest (module)</a>
</li>
</ul></td>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="stdlib.html#module-urllib">urllib (module)</a>
</li>
<li><a href="stdlib.html#urllib.urllib.urlopen">urllib.urlopen() (dans le module urllib)</a>
</li>
</ul></td>
</tr></table>
<h2 id="V">V</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li>
variable d&#39;environnement
<ul>
<li><a href="settings.html#envvar-PYTHONPATH">PYTHONPATH</a>, <a href="specialmethods.html#index-0">[1]</a>, <a href="specialmethods.html#index-1">[2]</a>, <a href="stdlib.html#index-0">[3]</a>
</li>
<li><a href="settings.html#envvar-PYTHONSTARTUP">PYTHONSTARTUP</a>
</li>
<li><a href="specialmethods.html#envvar-`sys.modules`">`sys.modules`</a>
</li>
<li><a href="stdlib.html#envvar-sys.argv">sys.argv</a>
</li>
<li><a href="stdlib.html#envvar-sys.path">sys.path</a>
</li>
</ul></li>
</ul></td>
</tr></table>
<h2 id="Y">Y</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
<td style="width: 33%; vertical-align: top;"><ul>
<li><a href="structures.html#term-yield"><strong>yield</strong></a>
</li>
</ul></td>
</tr></table>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="#"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="#" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,215 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Prise en main &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Mettre en place son environnement de travail" href="settings.html" />
<link rel="prev" title="Apprentissage de la programmation avec python" href="index.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="settings.html" title="Mettre en place son environnement de travail"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="index.html" title="Apprentissage de la programmation avec python"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="prise-en-main">
<h1>Prise en main<a class="headerlink" href="#prise-en-main" title="Lien permanent vers ce titre"></a></h1>
<p>Lobjectif de ce cours est de vous apprendre à programmer en
<a class="reference internal" href="#term-python"><span class="xref std std-term">python</span></a>. Ce cours a été fait avec <a class="reference internal" href="#term-sphinx"><span class="xref std std-term">sphinx</span></a>, loutil de
gestion de documentation en python utilisé pour documenter python lui-même.</p>
<p>Pour plus dinformation : <a class="reference internal" href="docutils.html"><span class="doc">Sphinx et docutils</span></a></p>
<p>Avec python :</p>
<ul>
<li><p class="first">vous navez pas grand chose à savoir pour arriver à faire beaucoup de choses,</p>
</li>
<li><p class="first">vous allez pouvoir travailler de manière</p>
<ul class="simple">
<li>entièrement autonome</li>
<li>rapide</li>
<li>agile (au sens des méthodes agiles)</li>
</ul>
</li>
<li><p class="first">vous allez progresser rapidement</p>
</li>
<li><p class="first">aucune connaissance préalable en programmation nest requise</p>
</li>
<li><p class="first">le hello world en une ligne:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">c</span> <span class="s2">&quot;print &#39;hello&#39;&quot;</span>
</pre></div>
</div>
</li>
<li><p class="first">rendre un fichier exécutable et ajouter le she bang:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="nb">print</span> <span class="s2">&quot;hello&quot;</span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">lorsquon lance python sur un programme, des fichiers
avec une extension <code class="docutils literal"><span class="pre">.pyc</span></code> apparaissent.</p>
</div>
<dl class="glossary docutils">
<dt id="term-python">python</dt>
<dd><a class="reference external" href="http://www.python.org">python</a> est un langage de programmation généraliste, libre, totalement
orienté objet, dynamiquement typé, semi-interprété ou, pour certaines
utilisations optimisées, compilé ou compilé à la volée (JIT).</dd>
<dt id="term-sphinx">sphinx</dt>
<dd><a class="reference external" href="http://sphinx.pocoo.org">sphinx</a> est un outil de documentation utilisant la syntaxe wiki
<a class="reference external" href="http://docutils.sf.net">docutils</a></dd>
</dl>
<ul class="simple">
<li>lorsquon lance python sans spécifier de nom de fichier, cest linterpréteur
python qui est lancé (le «&nbsp;prompt&nbsp;»)</li>
</ul>
<p>En python, le dicton le plus répandu est «&nbsp;there must be an obvious way
to do it&nbsp;», (il y a certainement une manière évidente de le faire en
python), <code class="docutils literal"><span class="pre">import</span> <span class="pre">this</span></code> permet de se remémorer les
dictons de python. Ce dicton est très différent de lapproche du perl
par exemple, qui présuppose : «&nbsp;there is more than one way to do it&nbsp;»,
cest-à-dire que en gros en perl, on peut le faire nimporte comment,
mais pas en python, enfin en python cest pas conseillé de le faire à sa
sauce, il y a en général une bonne pratique à découvrir et à mettre en place.</p>
<p>Taper «&nbsp;python&nbsp;» dans votre console</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s2">&quot;hello world&quot;</span>
<span class="go">hello world</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">this</span>
<span class="go">Beautiful is better than ugly.</span>
<span class="go">Explicit is better than implicit.</span>
<span class="go">Simple is better than complex.</span>
<span class="go">Complex is better than complicated.</span>
<span class="gp">...</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">Voir aussi</p>
<dl class="last docutils">
<dt>les modules, <a class="reference internal" href="specialmethods.html#namespaces"><span class="std std-ref">les espaces de nommage</span></a> et la librairie standard</dt>
<dd><a class="reference internal" href="stdlib.html"><span class="doc">La librairie standard</span></a></dd>
</dl>
</div>
<p>pour avoir de laide, taper dans le prompt :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">function</span><span class="p">)</span>
</pre></div>
</div>
<p>Le bon réflexe de chercher ce qui est le plus répandu et le plus utilisé est le
bon en python : on dit que python est livré «&nbsp;batteries included&nbsp;», ce qui
signifie que lorsquon a un besoin précis il faut chercher dans la librairie
standard python, puis dans les librairies les plus utilisées en python, puis en
dernier… le reste, ce qui est disponible. Mais si une librairie connue ne
fait pas exactement ce qui est attendu et quune libraire inconnue du bataillon
fait exactement ce qui est attendu, (et a lair de fonctionner
correctement…), alors il faut choisir la libraire inconnue au bataillon.</p>
<div class="section" id="usage-de-python">
<h2>usage de python<a class="headerlink" href="#usage-de-python" title="Lien permanent vers ce titre"></a></h2>
<p>à peu près tous les domaines de linformatique, du scripting système à la génération
de pdf en passant par le développement web et le développement rapide dapplications.</p>
<p>exemple : web server</p>
<p>pour créer un serveur web simplement:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">server</span><span class="o">.</span><span class="n">http</span> <span class="mi">8000</span> <span class="n">localhost</span>
</pre></div>
</div>
<p>exemple : utiliser python pour faire un fichier de conf</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">spam</span> <span class="o">=</span> <span class="s2">&quot;eggs&quot;</span>
<span class="n">actions</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">(</span><span class="s1">&#39;call_view&#39;</span><span class="p">,</span> <span class="s1">&#39;com.next&#39;</span><span class="p">)</span>
<span class="p">]</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="settings.html" title="Mettre en place son environnement de travail"
>suivant</a> |</li>
<li class="right" >
<a href="index.html" title="Apprentissage de la programmation avec python"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,207 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Apprentissage de la programmation avec python &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Prise en main" href="getting-started.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="getting-started.html" title="Prise en main"
accesskey="N">suivant</a> |</li>
<a href="#">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="apprentissage-de-la-programmation-avec-python">
<h1>Apprentissage de la programmation avec python<a class="headerlink" href="#apprentissage-de-la-programmation-avec-python" title="Lien permanent vers ce titre"></a></h1>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="getting-started.html">Prise en main</a><ul>
<li class="toctree-l2"><a class="reference internal" href="getting-started.html#usage-de-python">usage de python</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="settings.html">Mettre en place son environnement de travail</a><ul>
<li class="toctree-l2"><a class="reference internal" href="settings.html#les-editeurs-pour-python">Les éditeurs pour python</a></li>
<li class="toctree-l2"><a class="reference internal" href="settings.html#idle">IDLE</a></li>
<li class="toctree-l2"><a class="reference internal" href="settings.html#nano">nano</a></li>
<li class="toctree-l2"><a class="reference internal" href="settings.html#gedit">Gedit</a></li>
<li class="toctree-l2"><a class="reference internal" href="settings.html#vi">Vi</a></li>
<li class="toctree-l2"><a class="reference internal" href="settings.html#configurer-son-editeur-resume">configurer son éditeur : résumé</a></li>
<li class="toctree-l2"><a class="reference internal" href="settings.html#configurer-son-prompt-python">configurer son prompt python</a></li>
<li class="toctree-l2"><a class="reference internal" href="settings.html#consulter-la-librairie-standard">Consulter la librairie standard</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="type.html">Typage, types de base</a><ul>
<li class="toctree-l2"><a class="reference internal" href="type.html#unicode">unicode</a></li>
<li class="toctree-l2"><a class="reference internal" href="type.html#tuples-listes-dictionnaires">tuples, listes, dictionnaires</a></li>
<li class="toctree-l2"><a class="reference internal" href="type.html#difference-entre-type-et-isinstance">différence entre type et isinstance</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="structures.html">Structures de contrôle et fonctions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="structures.html#fonctions">fonctions</a></li>
<li class="toctree-l2"><a class="reference internal" href="structures.html#le-polymorphisme-parametrique">le polymorphisme paramétrique</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="testsunitaires.html">Tests unitaires et pile dappels</a><ul>
<li class="toctree-l2"><a class="reference internal" href="testsunitaires.html#options-utiles-dans-py-test">options utiles dans <cite>py.test</cite></a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="docutils.html">Sphinx et docutils</a><ul>
<li class="toctree-l2"><a class="reference internal" href="docutils.html#docutils">Docutils</a></li>
<li class="toctree-l2"><a class="reference internal" href="docutils.html#la-documentation-technique">La documentation technique</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="section" id="programmation-python-connaissances-de-base">
<h1>Programmation python, connaissances de base<a class="headerlink" href="#programmation-python-connaissances-de-base" title="Lien permanent vers ce titre"></a></h1>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="classes.html">Définir et manipuler des classes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="classes.html#programmation-objet-premiere-approche">programmation objet (première approche)</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#attribut-d-objets-et-de-classes">attribut dobjets et de classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#le-dict-avec-l-heritage-de-classe">le __dict__ avec lhéritage de classe</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#method-resolution-object">method resolution object</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#manipulations-sur-les-classes-et-les-objets">Manipulations sur les classes et les objets</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#les-patrons-de-conception">les patrons de conception</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#metaclasses">métaclasses</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="prompt.html">Interactions avec lutilisateur</a><ul>
<li class="toctree-l2"><a class="reference internal" href="prompt.html#les-prompts">les prompts</a></li>
<li class="toctree-l2"><a class="reference internal" href="prompt.html#le-module-cmd-et-les-interpreteurs">le module <code class="docutils literal"><span class="pre">cmd</span></code> et les interpréteurs</a></li>
<li class="toctree-l2"><a class="reference internal" href="prompt.html#lire-et-ecrire-dans-un-fichier">lire et écrire dans un fichier</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="specialmethods.html">Programmation python courante</a><ul>
<li class="toctree-l2"><a class="reference internal" href="specialmethods.html#les-espaces-de-nommage">les espaces de nommage</a></li>
<li class="toctree-l2"><a class="reference internal" href="specialmethods.html#modules-charges-et-modules-importes">modules chargés et modules importés</a></li>
<li class="toctree-l2"><a class="reference internal" href="specialmethods.html#connaitre-la-version-d-un-module">Connaître la version dun module</a></li>
<li class="toctree-l2"><a class="reference internal" href="specialmethods.html#les-methodes-speciales">Les méthodes spéciales</a></li>
<li class="toctree-l2"><a class="reference internal" href="specialmethods.html#attributs-et-accesseurs">Attributs et accesseurs</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="exceptions.html">Le style de programmation par exceptions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#la-regle-du-samourai">La règle du samouraï</a></li>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#utiliser-la-pile-d-appel-pour-debugger">utiliser la pile dappel pour débugger</a></li>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#les-exceptions-imbriquees">Les exceptions imbriquées</a></li>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#la-hierarchie-des-exceptions">La hiérarchie des exceptions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="DesignPatterns.html">Les design patterns</a><ul>
<li class="toctree-l2"><a class="reference internal" href="DesignPatterns.html#le-duck-typing">Le duck typing</a></li>
<li class="toctree-l2"><a class="reference internal" href="DesignPatterns.html#hold-or-wrap">hold or wrap ?</a></li>
<li class="toctree-l2"><a class="reference internal" href="DesignPatterns.html#wrapper-can-restrict-inheritance-cannot-restrict">wrapper can restrict, inheritance cannot restrict</a></li>
<li class="toctree-l2"><a class="reference internal" href="DesignPatterns.html#pattern-de-creation-singleton">Pattern de création : singleton</a></li>
<li class="toctree-l2"><a class="reference internal" href="DesignPatterns.html#la-factory">la factory</a></li>
<li class="toctree-l2"><a class="reference internal" href="DesignPatterns.html#template-method-self-delegation">template method (self delegation)</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="stdlib.html">La <code class="docutils literal"><span class="pre">librairie</span> <span class="pre">standard</span></code></a><ul>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#module-builtins">les builtins</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="section" id="recapitulatifs-de-la-formation">
<h1>Récapitulatifs de la formation<a class="headerlink" href="#recapitulatifs-de-la-formation" title="Lien permanent vers ce titre"></a></h1>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="exercices.html">Liste des exercices</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercices.html#exercices-a-faire">exercices à faire</a></li>
</ul>
</div>
</div>
<div class="section" id="index-et-recherche">
<h1>Index et recherche<a class="headerlink" href="#index-et-recherche" title="Lien permanent vers ce titre"></a></h1>
<ul class="simple">
<li><a class="reference internal" href="genindex.html"><span class="std std-ref">Index</span></a></li>
<li><a class="reference internal" href="py-modindex.html"><span class="std std-ref">Index du module</span></a></li>
<li><a class="reference internal" href="search.html"><span class="std std-ref">Page de recherche</span></a></li>
</ul>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="getting-started.html" title="Prise en main"
>suivant</a> |</li>
<a href="#">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,119 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>&lt;no title&gt; &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<p>Bonjour à toute la promo,</p>
<p>Comme convenu, voici quelques liens (algorithmiques et autres)</p>
<p>Dabord, python :)</p>
<p><a class="reference external" href="https://www.python.org/">https://www.python.org/</a></p>
<p>et le tuto dive into python</p>
<p><a class="reference external" href="http://www.diveintopython3.net/">http://www.diveintopython3.net/</a></p>
<p>et le fameux python challenge</p>
<p><a class="reference external" href="http://www.pythonchallenge.com/">http://www.pythonchallenge.com/</a></p>
<p>cest un challenge algorithmique quon peut résoudre avec du python mais pas forcément, on peut utiliser nimporte quel langage.</p>
<p>Ceux qui dépasseront la sixième étape (sans regarder les soluces) auront droit à mon respect :)</p>
<p>Ensuite, la librairie pandas que nous avons vue :</p>
<p><a class="reference external" href="http://pandas.pydata.org/">http://pandas.pydata.org/</a></p>
<p>et pandas sur python-simple</p>
<p><a class="reference external" href="http://www.python-simple.com/python-pandas/stacking-unstacking-dataframe.php">http://www.python-simple.com/python-pandas/stacking-unstacking-dataframe.php</a></p>
<p>Sinon après il y a plein de livres, notamment le wikilivre</p>
<p><a class="reference external" href="https://fr.wikibooks.org/wiki/Programmation_algorithmique/Sommaire">https://fr.wikibooks.org/wiki/Programmation_algorithmique/Sommaire</a></p>
<p><a class="reference external" href="https://fr.wikibooks.org/wiki/Cat%C3%A9gorie:Programmation_algorithmique_(livre">https://fr.wikibooks.org/wiki/Cat%C3%A9gorie:Programmation_algorithmique_(livre</a>)</p>
<p><a class="reference external" href="https://fr.wikibooks.org/wiki/Programmation">https://fr.wikibooks.org/wiki/Programmation</a></p>
<p>après sur wikipédia il y a plein de pages consacrée à divers algorithmes (le voyageur de commerce, les algoritmes tirés de la biologie, etc…) mais on na pas vu ça en détails.</p>
<p>après il y a une bonne présentation des modules et sous-modules (mais cest de locaml)</p>
<p><a class="reference external" href="https://www.good-eris.net/formation-ocaml/modules/submod.html">https://www.good-eris.net/formation-ocaml/modules/submod.html</a></p>
<p>vous pouvez aussi vous y mettre :</p>
<p><a class="reference external" href="https://www.good-eris.net/formation-ocaml/intro.html">https://www.good-eris.net/formation-ocaml/intro.html</a></p>
<p>un très bon livre pour ocaml</p>
<p><a class="reference external" href="http://programmer-avec-ocaml.lri.fr/chap10.html">http://programmer-avec-ocaml.lri.fr/chap10.html</a></p>
<p>de très bon livres pour apprendre le python existent aussi, notamment ceux de Tarek Ziadé (un français qui habite en Bourgogne).</p>
<p>Voilà</p>
<p>Très bonne continuation à vous tous, à bientôt
Gwen</p>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

Binary file not shown.

View File

@ -0,0 +1,271 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Interactions avec lutilisateur &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Programmation python courante" href="specialmethods.html" />
<link rel="prev" title="Définir et manipuler des classes" href="classes.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="specialmethods.html" title="Programmation python courante"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="classes.html" title="Définir et manipuler des classes"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="interactions-avec-l-utilisateur">
<h1>Interactions avec lutilisateur<a class="headerlink" href="#interactions-avec-l-utilisateur" title="Lien permanent vers ce titre"></a></h1>
<div class="section" id="les-prompts">
<h2>les prompts<a class="headerlink" href="#les-prompts" title="Lien permanent vers ce titre"></a></h2>
<p><cite>raw_input</cite> ou <cite>input</cite></p>
<p>(raw_input renvoie une string, input essayes dévaluer, soyez prudent…)</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">subprocess</span> <span class="k">import</span> <span class="n">call</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filename</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s2">&quot;quel fichier voulez-vous afficher ?</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">call</span><span class="p">(</span><span class="s2">&quot;cat &quot;</span> <span class="o">+</span> <span class="n">filename</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="le-module-cmd-et-les-interpreteurs">
<span id="cmdlabel"></span><h2>le module <a class="reference internal" href="#module-cmd" title="cmd: interpréteur ligne de commande"><code class="xref py py-mod docutils literal"><span class="pre">cmd</span></code></a> et les interpréteurs<a class="headerlink" href="#le-module-cmd-et-les-interpreteurs" title="Lien permanent vers ce titre"></a></h2>
<p>le monde des interpréteur ligne de commande…</p>
<p>Peu après lâge de bronze vint le temps de linterpréteur ligne de commande,
cest-à-dire quelque chose de plus spécifique que <strong>lapplication ligne de commande</strong>,
ou que lutilitaire ligne de commande.</p>
<p>Un interpréteur ligne de commande est un programme qui :</p>
<ul class="simple">
<li>est forcément plein texte</li>
<li>vous donne un prompt</li>
<li>prends toutes ses entrées dun coup</li>
<li>produit une sortie (typiquement des lignes de texte)</li>
<li>vous redonne un prompt</li>
</ul>
<p>Le shell unix est un bon exemple dinterpréteur ligne de commande.</p>
<p>Un utilitaire ligne de commande est un programme unix-like qui prend toutes
les entrées dun coup, et qui vous renvoie une sortie dun coup.</p>
<p>le module <a class="reference internal" href="#module-cmd" title="cmd: interpréteur ligne de commande"><code class="xref py py-mod docutils literal"><span class="pre">cmd</span></code></a> : exemple dutilisation</p>
<span class="target" id="module-cmd"></span><div class="highlight-default"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="c1"># -*- coding: utf8 -*-</span>
<span class="sd">&quot;&quot;&quot;Command line interpreter</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="kn">import</span> <span class="nn">cmd</span>
<span class="c1"># ____________________________________________________________</span>
<span class="c1"># this Cli is a model of a basic use of a simple cmd</span>
<span class="k">class</span> <span class="nc">Cli</span><span class="p">(</span><span class="n">cmd</span><span class="o">.</span><span class="n">Cmd</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">cmd</span><span class="o">.</span><span class="n">Cmd</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">doc_header</span> <span class="o">=</span> <span class="s2">&quot;Documented commands (type help &lt;command&gt;):&quot;</span>
<span class="bp">self</span><span class="o">.</span><span class="n">undoc_header</span> <span class="o">=</span> <span class="s2">&quot;Undocumented commands&quot;</span>
<span class="bp">self</span><span class="o">.</span><span class="n">prompt</span> <span class="o">=</span> <span class="s2">&quot;#Prompt&gt; &quot;</span>
<span class="bp">self</span><span class="o">.</span><span class="n">intro</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;cli (command line interpreter)</span>
<span class="s2">(type help or ? for commands list)&quot;&quot;&quot;</span>
<span class="bp">self</span><span class="o">.</span><span class="n">ruler</span> <span class="o">=</span> <span class="s2">&quot;-&quot;</span>
<span class="k">def</span> <span class="nf">emptyline</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="nb">print</span> <span class="s2">&quot;Type &#39;exit&#39; to finish withe the session or type ? for help.&quot;</span>
<span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
<span class="nb">print</span> <span class="s2">&quot;unknown command prefix&quot;</span>
<span class="nb">print</span> <span class="s2">&quot;*** unknown syntax : </span><span class="si">%s</span><span class="s2"> (type &#39;help&#39; for help for a list of valid commands)&quot;</span><span class="o">%</span><span class="n">line</span>
<span class="bp">self</span><span class="o">.</span><span class="n">emptyline</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">do_exit</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Exits from the console&quot;&quot;&quot;</span>
<span class="k">return</span> <span class="kc">True</span>
<span class="k">def</span> <span class="nf">do_quit</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
<span class="k">return</span> <span class="kc">True</span>
<span class="k">def</span> <span class="nf">do_EOF</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">args</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;Exit on system end of file character&quot;&quot;&quot;</span>
<span class="k">return</span> <span class="kc">True</span>
<span class="c1"># ____________________________________________________________</span>
<span class="c1"># commands pre and post actions</span>
<span class="c1"># def precmd(self, line):</span>
<span class="c1"># return line</span>
<span class="c1"># def postcmd(self, stop, line):</span>
<span class="c1"># # if there is a problem, just return True : it stops everythings</span>
<span class="c1"># stop = True</span>
<span class="c1"># return stop # quit if stop == True</span>
<span class="c1"># ____________________________________________________________</span>
<span class="c1"># program pre and post actions</span>
<span class="c1"># def preloop(self):</span>
<span class="c1"># # action for the beginning of the program</span>
<span class="c1"># pass</span>
<span class="c1"># def postloop(self):</span>
<span class="c1"># # action for the end of the program</span>
<span class="c1"># print &quot;exit cli&quot;</span>
<span class="c1"># ____________________________________________________________</span>
<span class="k">class</span> <span class="nc">HelloCli</span><span class="p">(</span><span class="n">Cli</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">input_hello</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
<span class="k">return</span> <span class="n">line</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">&quot;,&quot;</span><span class="p">,</span> <span class="s2">&quot; and &quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">output_hello</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">result</span><span class="p">):</span>
<span class="nb">print</span> <span class="n">result</span>
<span class="k">def</span> <span class="nf">do_hello</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">output_hello</span><span class="p">(</span><span class="s2">&quot;hello, &quot;</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">input_hello</span><span class="p">(</span><span class="n">line</span><span class="p">))</span>
<span class="c1">#return False # if you want to stay into the cli</span>
<span class="k">return</span> <span class="kc">True</span> <span class="c1"># if you want to exit</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
<span class="n">prompt</span> <span class="o">=</span> <span class="n">HelloCli</span><span class="p">()</span>
<span class="n">prompt</span><span class="o">.</span><span class="n">cmdloop</span><span class="p">(</span><span class="s2">&quot;intro, modifies Cmd.intro&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference download internal" href="_downloads/cli.py" download=""><code class="xref download docutils literal"><span class="pre">telecharger</span> <span class="pre">cmd</span></code></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">cli</span> <span class="k">import</span> <span class="n">Cli</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prompt</span> <span class="o">=</span> <span class="n">Cli</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prompt</span><span class="o">.</span><span class="n">cmdloop</span><span class="p">()</span>
<span class="go">cli (command line interpreter)</span>
<span class="go">(type help or ? for commands list)</span>
<span class="go">#Prompt&gt; ?</span>
<span class="go">Documented commands (type help &lt;command&gt;):</span>
<span class="go">==========================================</span>
<span class="go">EOF exit</span>
<span class="go">Undocumented commands:</span>
<span class="go">======================</span>
<span class="go">cmd help quit</span>
<span class="go">#Prompt&gt;</span>
</pre></div>
</div>
<p>pour ajouter une commande, utiliser simplement lhéritage:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">cli</span> <span class="k">import</span> <span class="n">Cli</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Prompt</span><span class="p">(</span><span class="n">Cli</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">do_hello</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">line</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="s2">&quot;hello </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">line</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prompt</span> <span class="o">=</span> <span class="n">Prompt</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prompt</span><span class="o">.</span><span class="n">cmdloop</span><span class="p">()</span>
<span class="go">cli (command line interpreter)</span>
<span class="go">(type help or ? for commands list)</span>
<span class="go">#Prompt&gt; ?</span>
<span class="go">Documented commands (type help &lt;command&gt;):</span>
<span class="go">==========================================</span>
<span class="go">EOF exit</span>
<span class="go">Undocumented commands:</span>
<span class="go">======================</span>
<span class="go">cmd hello help quit</span>
<span class="go">#Prompt&gt; hello world</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-0">
<p class="first admonition-title">À faire</p>
<p class="last">faire un petit projet dinterpréteur ligne de commande du jeu C+/C-</p>
</div>
</div>
<div class="section" id="lire-et-ecrire-dans-un-fichier">
<h2>lire et écrire dans un fichier<a class="headerlink" href="#lire-et-ecrire-dans-un-fichier" title="Lien permanent vers ce titre"></a></h2>
<p>les <strong>handle de fichier</strong> (file handles)</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fh</span> <span class="o">=</span> <span class="n">file</span><span class="p">(</span><span class="s1">&#39;test&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fh</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;hello world&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fh</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">content</span> <span class="o">=</span> <span class="n">file</span><span class="p">(</span><span class="s1">&#39;test&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">content</span>
<span class="go">&#39;hello world&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="specialmethods.html" title="Programmation python courante"
>suivant</a> |</li>
<li class="right" >
<a href="classes.html" title="Définir et manipuler des classes"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,253 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Index des modules Python &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<script type="text/javascript">
DOCUMENTATION_OPTIONS.COLLAPSE_INDEX = true;
</script>
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="#" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<h1>Index des modules Python</h1>
<div class="modindex-jumpbox">
<a href="#cap-a"><strong>a</strong></a> |
<a href="#cap-b"><strong>b</strong></a> |
<a href="#cap-c"><strong>c</strong></a> |
<a href="#cap-d"><strong>d</strong></a> |
<a href="#cap-g"><strong>g</strong></a> |
<a href="#cap-h"><strong>h</strong></a> |
<a href="#cap-i"><strong>i</strong></a> |
<a href="#cap-o"><strong>o</strong></a> |
<a href="#cap-p"><strong>p</strong></a> |
<a href="#cap-r"><strong>r</strong></a> |
<a href="#cap-s"><strong>s</strong></a> |
<a href="#cap-t"><strong>t</strong></a> |
<a href="#cap-u"><strong>u</strong></a>
</div>
<table class="indextable modindextable">
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-a"><td></td><td>
<strong>a</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-abc"><code class="xref">abc</code></a></td><td>
<em>les abstract base classes</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-b"><td></td><td>
<strong>b</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-builtins"><code class="xref">builtins</code></a></td><td>
<em>les fonctions directement à disposition sans import spécifique</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-c"><td></td><td>
<strong>c</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="prompt.html#module-cmd"><code class="xref">cmd</code></a></td><td>
<em>interpréteur ligne de commande</em></td></tr>
<tr>
<td></td>
<td>
<a href="type.html#module-collections"><code class="xref">collections</code></a></td><td>
<em>autres types de données</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-d"><td></td><td>
<strong>d</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-doctest"><code class="xref">doctest</code></a></td><td>
<em>module de tests unitaires basé sur les docstrings</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-g"><td></td><td>
<strong>g</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-getpass"><code class="xref">getpass</code></a></td><td>
<em>recupération des mots de passe en ligne de commande</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-h"><td></td><td>
<strong>h</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-hotshot"><code class="xref">hotshot</code></a></td><td>
<em>benchmark</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-i"><td></td><td>
<strong>i</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-IPy"><code class="xref">IPy</code></a></td><td>
<em>traitement des ips en python &lt; python 3.3 remplacé par ipadress</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-o"><td></td><td>
<strong>o</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-optparse"><code class="xref">optparse</code></a></td><td>
<em>parsing de la ligne de commande</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-p"><td></td><td>
<strong>p</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="testsunitaires.html#module-pdb"><code class="xref">pdb</code></a></td><td>
<em>debugger de la lib standard</em></td></tr>
<tr>
<td><img src="_static/minus.png" class="toggler"
id="toggle-1" style="display: none" alt="-" /></td>
<td>
<code class="xref">py</code></td><td>
<em></em></td></tr>
<tr class="cg-1">
<td></td>
<td>&#160;&#160;&#160;
<a href="testsunitaires.html#module-py.test"><code class="xref">py.test</code></a></td><td>
<em>outil de test unitaires de la pylib</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-r"><td></td><td>
<strong>r</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="type.html#module-regexp"><code class="xref">regexp</code></a></td><td>
<em>expression régulières</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-s"><td></td><td>
<strong>s</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-shelve"><code class="xref">shelve</code></a></td><td>
<em>linéarisation de données</em></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-subprocess"><code class="xref">subprocess</code></a></td><td>
<em>exécuter une commande shell, récupérer le code retour et la sortie</em></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-sys"><code class="xref">sys</code></a></td><td>
<em>paramètres et fonctions systèmes</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-t"><td></td><td>
<strong>t</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-time"><code class="xref">time</code></a></td><td>
<em>caculs de temps</em></td></tr>
<tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
<tr class="cap" id="cap-u"><td></td><td>
<strong>u</strong></td><td></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-unittest"><code class="xref">unittest</code></a></td><td>
<em>module de tests unitaires</em></td></tr>
<tr>
<td></td>
<td>
<a href="stdlib.html#module-urllib"><code class="xref">urllib</code></a></td><td>
<em>parse des urls</em></td></tr>
</table>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="#" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,119 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Recherche &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<script type="text/javascript" src="_static/searchtools.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="#" />
<script type="text/javascript">
jQuery(function() { Search.loadIndex("searchindex.js"); });
</script>
<script type="text/javascript" id="searchindexloader"></script>
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<h1 id="search-documentation">Recherche</h1>
<div id="fallback" class="admonition warning">
<script type="text/javascript">$('#fallback').hide();</script>
<p>
Veuillez activer le JavaScript pour que la recherche fonctionne.
</p>
</div>
<p>
Vous pouvez effectuer une recherche au sein des documents. Saisissez les termes
de votre recherche dans le champs ci-dessous et cliquez sur "rechercher". Notez que la fonctionnalité de recherche
va automatiquement chercher l'ensemble des mots. Les pages
contenant moins de mots n'apparaîtront pas dans la liste des résultats.
</p>
<form action="" method="get">
<input type="text" name="q" value="" />
<input type="submit" value="rechercher" />
<span id="search-progress" style="padding-left: 10px"></span>
</form>
<div id="search-results">
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="#"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,289 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Mettre en place son environnement de travail &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Typage, types de base" href="type.html" />
<link rel="prev" title="Prise en main" href="getting-started.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="type.html" title="Typage, types de base"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="getting-started.html" title="Prise en main"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="mettre-en-place-son-environnement-de-travail">
<h1>Mettre en place son environnement de travail<a class="headerlink" href="#mettre-en-place-son-environnement-de-travail" title="Lien permanent vers ce titre"></a></h1>
<div class="section" id="les-editeurs-pour-python">
<h2>Les éditeurs pour python<a class="headerlink" href="#les-editeurs-pour-python" title="Lien permanent vers ce titre"></a></h2>
<p>Nimporte quel éditeur qui respecte les coding standards du pep8 convient :</p>
<p><a class="reference external" href="https://www.python.org/dev/peps/pep-0008/">https://www.python.org/dev/peps/pep-0008/</a></p>
<p><a class="reference external" href="https://pep8.org/">pep8</a></p>
<p>dune manière générale, de base un éditeur spartiate peut convenir du moment
que lintentation de 4 espaces est respectée et que les tablulations sont
remplacées par des espaces, car le plus important en python cest lindentation,
et le fait de bien voir ou est le règlage de lencodage (ça doit être en <code class="docutils literal"><span class="pre">utf-8</span></code>)
Pour voir si ton éditeur est bien configuré, tu prends nimporte quel fichier python
que tu as créé, puis tu faire un</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">pep8</span> <span class="o">&lt;</span><span class="n">mon_fichier</span><span class="o">.</span><span class="n">py</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>et <code class="docutils literal"><span class="pre">pep</span></code> va dire ce qui ne va pas en termes de syntaxe.</p>
</div>
<div class="section" id="idle">
<h2>IDLE<a class="headerlink" href="#idle" title="Lien permanent vers ce titre"></a></h2>
<p><a class="reference external" href="https://docs.python.org/2/library/idle.html">https://docs.python.org/2/library/idle.html</a></p>
<p>Pour information, IDLE est un éditeur intégré (dans la lib standard de python)
mais je te le déconseille (trop spartiate).</p>
<p>un framework de développement intégré : <a class="reference internal" href="#term-idle"><span class="xref std std-term">IDLE</span></a></p>
<dl class="glossary docutils">
<dt id="term-idle">IDLE</dt>
<dd><a class="reference external" href="http://docs.python.org/2/library/idle.html">IDLE</a> est un IDE (environnement de développement intégré) mis à disposition
dans la <a class="reference internal" href="#term-librairie-standard"><span class="xref std std-term">librairie standard</span></a> de python</dd>
</dl>
</div>
<div class="section" id="nano">
<h2>nano<a class="headerlink" href="#nano" title="Lien permanent vers ce titre"></a></h2>
<p>pour lexemple, avec <strong>nano</strong>, voici comment faire une config qui permette
de coder en python. On configure nano avec le <code class="docutils literal"><span class="pre">.nanorc</span></code></p>
<p>Exemple de <code class="docutils literal"><span class="pre">.nanorc</span></code></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># replace les tabulations par 4 espaces</span>
<span class="nb">set</span> <span class="n">tabsize</span> <span class="mi">4</span>
<span class="nb">set</span> <span class="n">tabstospaces</span>
<span class="c1"># indente automatiquement</span>
<span class="nb">set</span> <span class="n">autoindent</span>
<span class="c1"># la touche home renvoie en debut de code</span>
<span class="nb">set</span> <span class="n">smarthome</span>
<span class="c1"># ne met pas de retour chariot a la fin d&#39;une ligne</span>
<span class="c1"># si elle depasse la largeur du terminal</span>
<span class="nb">set</span> <span class="n">nowrap</span>
<span class="n">unset</span> <span class="n">softwrap</span>
<span class="c1"># chargement de plusieur fichiers</span>
<span class="nb">set</span> <span class="n">multibuffer</span>
<span class="c1"># coloration syntaxique</span>
<span class="c1">## Python</span>
<span class="c1">#include &quot;/usr/share/nano/python.nanorc&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="gedit">
<h2>Gedit<a class="headerlink" href="#gedit" title="Lien permanent vers ce titre"></a></h2>
<p>Gedit cest très bien pour coder en python, mais de base cest pas sur un serveur,
il faut pouvoir être en mode graphique.
Il faut règler lindentation à 4 espaces pour respecter le pep8.
Et règler le replacement des tablulations par des espaces.
Mais surtout, très vite il faut installer les paquets additionnels, notamment
pour que gedit supprime les espaces en fin de ligne par exemple.</p>
<p>Je lutilise souvent mais il faut des plugins avec
genre ceux-ci (si tu es sur ubuntu):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">apt</span><span class="o">-</span><span class="n">get</span> <span class="n">install</span> <span class="n">gedit</span><span class="o">-</span><span class="n">plugins</span>
</pre></div>
</div>
<p>dans ce paquet par exemple, loutil pour commenter-décommenter le code est intéressant
(sélection dun paragraphe, puis Ctrl-M)
tu peux régler après la complétion des parenthèses, etc.</p>
<p>il y a aussi le paquet developer plugins :</p>
<p><a class="reference external" href="https://apps.ubuntu.com/cat/applications/gedit-developer-plugins/">https://apps.ubuntu.com/cat/applications/gedit-developer-plugins/</a></p>
<p>Après avec les plugins gedit commence à bien tenir la route.</p>
</div>
<div class="section" id="vi">
<h2>Vi<a class="headerlink" href="#vi" title="Lien permanent vers ce titre"></a></h2>
<p>Toujours la même problématiques (espaces, tablulation…)
Donc voici une partie de <code class="docutils literal"><span class="pre">.vimrc</span></code> qui le fait:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="s2">&quot;Pour le collage&quot;</span>
<span class="nb">set</span> <span class="n">pt</span><span class="o">=&lt;</span><span class="n">F5</span><span class="o">&gt;</span>
<span class="nb">set</span> <span class="n">vb</span> <span class="n">t_vb</span><span class="o">=</span><span class="s2">&quot;</span>
<span class="nb">set</span> <span class="n">shiftwidth</span><span class="o">=</span><span class="mi">4</span>
<span class="nb">set</span> <span class="n">expandtab</span>
<span class="nb">set</span> <span class="n">ts</span><span class="o">=</span><span class="mi">4</span>
<span class="nb">set</span> <span class="n">sw</span><span class="o">=</span><span class="mi">4</span>
<span class="n">syntax</span> <span class="n">on</span>
<span class="n">filetype</span> <span class="n">indent</span> <span class="n">on</span>
<span class="n">filetype</span> <span class="n">plugin</span> <span class="n">on</span>
<span class="nb">set</span> <span class="n">autoindent</span>
<span class="nb">set</span> <span class="n">hlsearch</span> <span class="s2">&quot; Surligne les resultats de recherche</span>
<span class="nb">set</span> <span class="n">wrap</span> <span class="s2">&quot; Pas de retour a la ligne auto (affichage)</span>
<span class="nb">set</span> <span class="n">showmatch</span> <span class="s2">&quot; Affiche parenthese correspondante</span>
<span class="nb">set</span> <span class="n">softtabstop</span><span class="o">=</span><span class="mi">4</span> <span class="s2">&quot; Largeur d&#39;une tabulation</span>
<span class="s2">&quot;set fdm=indent &quot;</span> <span class="n">Repli</span> <span class="n">selon</span> <span class="n">l</span><span class="s1">&#39;indentation</span>
</pre></div>
</div>
<p>maintenant après il y a un python-mode assez avancé qui permet de faire pas mal de choses.
(valider avec la syntaxe avec pylint, valider le pep8…)
Mais il faut une config plus avancée.</p>
<p>Dune manière générale, il y a la possibilité de valider avec des outils externes (pylint, pychecker, pep8…) et il y a aussi la possibilité de valider tout ça dans un éditeur.</p>
</div>
<div class="section" id="configurer-son-editeur-resume">
<h2>configurer son éditeur : résumé<a class="headerlink" href="#configurer-son-editeur-resume" title="Lien permanent vers ce titre"></a></h2>
<ul class="simple">
<li>les fichiers sources ont lextension <code class="docutils literal"><span class="pre">.py</span></code></li>
<li>une instruction par ligne</li>
<li>les blocs sont marqués par lindentation (utilser 4 espaces), règler
léditeur pour transformer les tabulations en espaces</li>
</ul>
</div>
<div class="section" id="configurer-son-prompt-python">
<h2>configurer son prompt python<a class="headerlink" href="#configurer-son-prompt-python" title="Lien permanent vers ce titre"></a></h2>
<dl class="envvar">
<dt id="envvar-PYTHONPATH">
<code class="descname">PYTHONPATH</code><a class="headerlink" href="#envvar-PYTHONPATH" title="Lien permanent vers cette définition"></a></dt>
<dd><p>pointe par défaut sur le répertoire courant, il est possible dajouter
un path</p>
</dd></dl>
<p>à mettre dans votre <code class="docutils literal"><span class="pre">.bashrc</span></code> :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>export PYTHONPATH:`pwd`
export PYTHONPATH=$PYTHONPATH:&#39;/usr/share&#39;:&#39;/toto/titi/tata&#39;
alias pyenv=&#39;export PYTHONPATH=`pwd`:$PYTHONPATH&#39;
export PYTHONSTARTUP=&#39;/home/gwen/.pystartup&#39;
</pre></div>
</div>
<dl class="envvar">
<dt id="envvar-PYTHONSTARTUP">
<code class="descname">PYTHONSTARTUP</code><a class="headerlink" href="#envvar-PYTHONSTARTUP" title="Lien permanent vers cette définition"></a></dt>
<dd><p>les trucs à mettre dans vos pytstartups (comme dans vos .bashrc)</p>
<ul class="simple">
<li>autocomplétion</li>
<li>affichage de lhistorique</li>
</ul>
</dd></dl>
<p>exemple de <code class="docutils literal"><span class="pre">.pystartup</span></code></p>
<p>à télécharger ici : <a class="reference download internal" href="_downloads/pystartup" download=""><code class="xref download docutils literal"><span class="pre">snippets/pystartup</span></code></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1"># Store the file in ~/.pystartup, and set an environment variable to point to</span>
<span class="c1"># it, e.g. &quot;export PYTHONSTARTUP=/max/home/itamar/.pystartup&quot; in bash.</span>
<span class="c1">#</span>
<span class="c1"># Note that PYTHONSTARTUP does *not* expand &quot;~&quot;, so you have to put in the full</span>
<span class="c1"># path to your home directory.</span>
<span class="kn">import</span> <span class="nn">rlcompleter</span>
<span class="kn">import</span> <span class="nn">readline</span>
<span class="n">readline</span><span class="o">.</span><span class="n">parse_and_bind</span><span class="p">(</span><span class="s2">&quot;tab: complete&quot;</span><span class="p">)</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="n">histfile</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&quot;HOME&quot;</span><span class="p">],</span> <span class="s2">&quot;.pyhist&quot;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">readline</span><span class="o">.</span><span class="n">read_history_file</span><span class="p">(</span><span class="n">histfile</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span>
<span class="k">pass</span>
<span class="kn">import</span> <span class="nn">atexit</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">readline</span><span class="o">.</span><span class="n">write_history_file</span><span class="p">,</span> <span class="n">histfile</span><span class="p">)</span>
<span class="k">del</span> <span class="n">os</span><span class="p">,</span> <span class="n">histfile</span>
<span class="c1"># enhanced completion</span>
<span class="c1">#import rlcompleter2</span>
<span class="c1">#rlcompleter2.setup()</span>
</pre></div>
</div>
</div>
<div class="section" id="consulter-la-librairie-standard">
<h2>Consulter la librairie standard<a class="headerlink" href="#consulter-la-librairie-standard" title="Lien permanent vers ce titre"></a></h2>
<dl class="glossary docutils">
<dt id="term-librairie-standard">librairie standard</dt>
<dd>Une des règles de base de python est quil existe certainement une manière
conseillé de faire une tâche en python. Le premier réflexe est daller
voir dans la <a class="reference external" href="http://docs.python.org/2.7/library/index.html">librairie standard</a></dd>
</dl>
<p>Premier réflexe : la doc en ligne ou bien installée sur votre disque dur.</p>
<p>la page daccueil de la doc officielle python :</p>
<img alt="_images/DocPython.png" src="_images/DocPython.png" />
<p>et surtout, une fois la librairie standard abordée, la page dindex des
modules :</p>
<img alt="_images/ModuleIndex.png" src="_images/ModuleIndex.png" />
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="type.html" title="Typage, types de base"
>suivant</a> |</li>
<li class="right" >
<a href="getting-started.html" title="Prise en main"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,359 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Programmation python courante &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Le style de programmation par exceptions" href="exceptions.html" />
<link rel="prev" title="Interactions avec lutilisateur" href="prompt.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="exceptions.html" title="Le style de programmation par exceptions"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="prompt.html" title="Interactions avec lutilisateur"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="programmation-python-courante">
<h1>Programmation python courante<a class="headerlink" href="#programmation-python-courante" title="Lien permanent vers ce titre"></a></h1>
<div class="section" id="les-espaces-de-nommage">
<span id="namespaces"></span><h2>les espaces de nommage<a class="headerlink" href="#les-espaces-de-nommage" title="Lien permanent vers ce titre"></a></h2>
<p>Lespace de nommage le plus courant est lorganisation en modules et en packages.</p>
<p>Packages et modules:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">package</span><span class="o">/</span>
<span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">module1</span><span class="o">.</span><span class="n">py</span>
<span class="n">subpackage</span><span class="o">/</span>
<span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">module2</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>A utilser pour organiser votre projet
Permet de minimiser les risques de conflits de nome
Permet de diminuer les entrées dans le <span class="target" id="index-0"></span><a class="reference internal" href="settings.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal"><span class="pre">PYTHONPATH</span></code></a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">package.module1</span>
<span class="kn">from</span> <span class="nn">package.subpackage</span> <span class="k">import</span> <span class="n">module2</span>
<span class="kn">from</span> <span class="nn">package.subpackage.module2</span> <span class="k">import</span> <span class="n">name</span>
</pre></div>
</div>
<ul class="simple">
<li>le fichier <cite>__init__.py</cite></li>
<li><cite>reload(module)</cite> au prompt</li>
<li>dangereux : limport «&nbsp;*&nbsp;», utiliser lattribut spécial <cite>__all__</cite> pour limport
sélectif</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">os</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
<p>lance un module en tant que script :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
<span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>Organisation modulaire</p>
<ul class="simple">
<li>construire des composants élémentaires</li>
<li>combiner ces composants</li>
<li>utiliser une structure pyramidale : les composants sont les éléments de
composants plus complexes.</li>
<li>découplage de lensemble en composants indépendants (gros programmes réalisables)</li>
<li>donner de la structure (rendre les gros programmes compréhensibles)</li>
<li>spécifier les liens entre les composants (rendre les programmes maintenables)</li>
<li>identifier les sous-composants indépendants (rendre les programmes réutilisables)</li>
<li>forcer labstraction (augmenter la sureté du programme)</li>
</ul>
</div>
<div class="section" id="modules-charges-et-modules-importes">
<h2>modules chargés et modules importés<a class="headerlink" href="#modules-charges-et-modules-importes" title="Lien permanent vers ce titre"></a></h2>
<p>Les modules susceptibles dêtre chargés sont dans le <span class="target" id="index-1"></span><a class="reference internal" href="settings.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal"><span class="pre">PYTHONPATH</span></code></a>.
Mais comment peut-on savoir ou ils sont physiquement (sur le disque dur) ?</p>
<dl class="envvar">
<dt id="envvar-`sys.modules`">
<code class="descname">`sys.modules`</code><a class="headerlink" href="#envvar-`sys.modules`" title="Lien permanent vers cette définition"></a></dt>
<dd></dd></dl>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;twisted&#39;</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">twisted</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;twisted&#39;</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="s1">&#39;twisted&#39;</span><span class="p">]</span>
<span class="go">&lt;module &#39;twisted&#39; from &#39;/usr/lib/python2.7/dist-packages/twisted/__init__.pyc&#39;&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition attention">
<p class="first admonition-title">Attention</p>
<p class="last">un module présent dans <cite>sys.modules</cite> nest pas forcément importé
dans lespace de nommage usuel. Il faut importer le module pour
pouvoir lutiliser.</p>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="s1">&#39;email&#39;</span><span class="p">]</span>
<span class="go">&lt;module &#39;email&#39; from &#39;/usr/lib/python2.7/email/__init__.pyc&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">email</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">name &#39;email&#39; is not defined</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Pour récupérer le chemin du module</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">print</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;.</span><span class="vm">__file__</span><span class="p">))</span>
</pre></div>
</div>
<p>Pour importer un module qui nest pas dans le <cite>sys.path</cite></p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">fch</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/path/to/mymodule/custom.py&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="n">my_module</span> <span class="o">=</span> <span class="n">imp</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="s1">&#39;dhcp_custom&#39;</span><span class="p">,</span> <span class="n">fch</span><span class="p">,</span> <span class="s1">&#39;/path/to/mymodule.py&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;.py&#39;</span><span class="p">,</span> <span class="s1">&#39;U&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="connaitre-la-version-d-un-module">
<h2>Connaître la version dun module<a class="headerlink" href="#connaitre-la-version-d-un-module" title="Lien permanent vers ce titre"></a></h2>
<p>Exemple : le module <code class="docutils literal"><span class="pre">datetime</span></code></p>
<p>Cest suivant la version de python car cest la librairie standard.</p>
<p>Sinon, en général il y a un attribut __version__</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sqlalchemy</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sqlalchemy</span><span class="o">.</span><span class="n">__version__</span>
<span class="go">&#39;0.9.8&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="les-methodes-speciales">
<h2>Les méthodes spéciales<a class="headerlink" href="#les-methodes-speciales" title="Lien permanent vers ce titre"></a></h2>
<p>méthodes spéciales correspondants aux interfaces des types de bases :</p>
<dl class="function">
<dt id="__init__">
<code class="descname">__init__</code><span class="sig-paren">(</span><em>self</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#__init__" title="Lien permanent vers cette définition"></a></dt>
<dt>
<code class="descname">le constructeur de l'instance d'objet</code></dt>
<dd></dd></dl>
<dl class="function">
<dt id="__add__">
<code class="descname">__add__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#__add__" title="Lien permanent vers cette définition"></a></dt>
<dd><p>correspond à la notation <cite>+</cite></p>
</dd></dl>
<p>exemple :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Zone</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">level</span> <span class="o">=</span> <span class="n">level</span>
<span class="k">def</span> <span class="nf">__add__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="n">Zone</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">+</span> <span class="n">other</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">level</span><span class="o">+</span><span class="n">other</span><span class="o">.</span><span class="n">level</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">__cmp__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">cmp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">level</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">level</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">specialmethods</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">=</span> <span class="n">Zone</span><span class="p">(</span><span class="s2">&quot;titi&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z2</span> <span class="o">=</span> <span class="n">Zone</span><span class="p">(</span><span class="s2">&quot;tutu&quot;</span><span class="p">,</span> <span class="mi">40</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">&gt;</span> <span class="n">z2</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">+</span> <span class="n">z2</span>
<span class="go">&lt;specialmethods.Zone object at 0x7f02d95fb190&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z3</span> <span class="o">=</span> <span class="n">z</span> <span class="o">+</span> <span class="n">z2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z3</span><span class="o">.</span><span class="n">name</span>
<span class="go">&#39;tititutu&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">z3</span><span class="o">.</span><span class="n">level</span>
<span class="go">50</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="attributs-et-accesseurs">
<h2>Attributs et accesseurs<a class="headerlink" href="#attributs-et-accesseurs" title="Lien permanent vers ce titre"></a></h2>
<p>python est un langage à attributs, cest-à-dire que le protocole daccès
aux attributs est règlable.</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">classattr</span> <span class="o">=</span> <span class="s2">&quot;a class attribute&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cobj</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cobj</span><span class="o">.</span><span class="n">classattr</span>
<span class="go">&#39;a class attribute&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cobj</span><span class="o">.</span><span class="n">insattr</span> <span class="o">=</span> <span class="s2">&quot;an instance attribute&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cobj</span><span class="o">.</span><span class="n">insattr</span>
<span class="go">&#39;an instance attribute&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">[</span><span class="s1">&#39;classattr&#39;</span><span class="p">]</span>
<span class="go">&#39;a class attribute&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cobj</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">[</span><span class="s1">&#39;insattr&#39;</span><span class="p">]</span>
<span class="go">&#39;an instance attribute&#39;</span>
</pre></div>
</div>
<p>les attributs ne sont pas systématiquement encapsulées en python.</p>
<p>pour contrôler laccès aux attributs, on utilise les méthodes spéciales:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="fm">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
<span class="fm">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">AnObject</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="o">......</span>
<span class="k">def</span> <span class="nf">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span>
<span class="k">if</span> <span class="n">name</span> <span class="o">==</span> <span class="s1">&#39;src&#39;</span><span class="p">:</span> <span class="c1">#do something</span>
<span class="c1"># this will assign the real object.name,</span>
<span class="c1">#despite __setattr__</span>
<span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">[</span><span class="n">name</span><span class="p">]</span><span class="o">=</span><span class="n">val</span>
<span class="k">def</span> <span class="nf">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
<span class="c1"># ...</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">func</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s2">&quot;method&quot;</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
<span class="o">...</span> <span class="n">deal</span> <span class="k">with</span> <span class="n">missing</span> <span class="n">method</span> <span class="o">...</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">func</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="n">func</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s2">&quot;method&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="n">callable</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
<span class="n">func</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
</pre></div>
</div>
<ul class="simple">
<li>un <strong>attribut</strong> spécial : <cite>__slots__</cite></li>
</ul>
<p>permet de fixer les attributs possibles dune classe</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Bar</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="vm">__slots__</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">,</span><span class="s2">&quot;b&quot;</span><span class="p">,</span><span class="s2">&quot;c&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Bar</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="s2">&quot;toto&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">a</span>
<span class="go">&#39;toto&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">d</span> <span class="o">=</span> <span class="s2">&quot;titi&quot;</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;Bar&#39; object has no attribute &#39;d&#39;</span>
</pre></div>
</div>
<div class="section" id="les-slots">
<h3>les slots<a class="headerlink" href="#les-slots" title="Lien permanent vers ce titre"></a></h3>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">lencapsulation nest pas une condition de base de la programmation
par objects, surtout que le contrôle nuit à lagilité.</p>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span> <span class="vm">__slots__</span> <span class="o">=</span> <span class="s1">&#39;x&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">z</span> <span class="o">=</span> <span class="mi">4</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;Point&#39; object has no attribute &#39;z&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>notation <cite>|</cite> et notation <cite>&gt;</cite></li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Test</span><span class="p">:</span>
<span class="n">nombre</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">def</span> <span class="nf">__or__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">nombre</span> <span class="o">+</span> <span class="n">other</span><span class="o">.</span><span class="n">nombre</span>
<span class="k">def</span> <span class="nf">__lshift__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">nombre</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">nombre</span> <span class="o">+</span> <span class="n">other</span><span class="o">.</span><span class="n">nombre</span>
<span class="n">t1</span> <span class="o">=</span> <span class="n">Test</span><span class="p">()</span>
<span class="n">t2</span> <span class="o">=</span> <span class="n">Test</span><span class="p">()</span>
<span class="n">t2</span><span class="o">.</span><span class="n">nombre</span> <span class="o">=</span> <span class="mi">2</span>
<span class="nb">print</span> <span class="n">t1</span> <span class="o">|</span> <span class="n">t2</span>
<span class="n">t1</span> <span class="o">&lt;&lt;</span> <span class="n">t2</span>
<span class="nb">print</span> <span class="n">t1</span><span class="o">.</span><span class="n">nombre</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="exceptions.html" title="Le style de programmation par exceptions"
>suivant</a> |</li>
<li class="right" >
<a href="prompt.html" title="Interactions avec lutilisateur"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,346 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>La librairie standard &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Liste des exercices" href="exercices.html" />
<link rel="prev" title="Les design patterns" href="DesignPatterns.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="exercices.html" title="Liste des exercices"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="DesignPatterns.html" title="Les design patterns"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="la-librairie-standard">
<h1>La <a class="reference internal" href="settings.html#term-librairie-standard"><span class="xref std std-term">librairie standard</span></a><a class="headerlink" href="#la-librairie-standard" title="Lien permanent vers ce titre"></a></h1>
<div class="section" id="module-builtins">
<span id="les-builtins"></span><h2>les builtins<a class="headerlink" href="#module-builtins" title="Lien permanent vers ce titre"></a></h2>
<ul class="simple">
<li>le module <a class="reference internal" href="#module-builtins" title="builtins: les fonctions directement à disposition sans import spécifique"><code class="xref py py-mod docutils literal"><span class="pre">builtins</span></code></a>, tout ce qui est accessible directement</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="s1">&#39;__builtins__&#39;</span><span class="p">)</span>
<span class="go">[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;,</span>
<span class="go">&#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getnewargs__&#39;,</span>
<span class="go">&#39;__getslice__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;,</span>
<span class="go">&#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;,</span>
<span class="go">&#39;__repr__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;,</span>
<span class="go">&#39;__subclasshook__&#39;, &#39;_formatter_field_name_split&#39;, &#39;_formatter_parser&#39;,</span>
<span class="go">&#39;capitalize&#39;, &#39;center&#39;, &#39;count&#39;, &#39;decode&#39;, &#39;encode&#39;, &#39;endswith&#39;, &#39;expandtabs&#39;,</span>
<span class="go">&#39;find&#39;, &#39;format&#39;, &#39;index&#39;, &#39;isalnum&#39;, &#39;isalpha&#39;, &#39;isdigit&#39;, &#39;islower&#39;,</span>
<span class="go">&#39;isspace&#39;, &#39;istitle&#39;, &#39;isupper&#39;, &#39;join&#39;, &#39;ljust&#39;, &#39;lower&#39;, &#39;lstrip&#39;,</span>
<span class="go">&#39;partition&#39;, &#39;replace&#39;, &#39;rfind&#39;, &#39;rindex&#39;, &#39;rjust&#39;, &#39;rpartition&#39;, &#39;rsplit&#39;,</span>
<span class="go">&#39;rstrip&#39;, &#39;split&#39;, &#39;splitlines&#39;, &#39;startswith&#39;, &#39;strip&#39;, &#39;swapcase&#39;, &#39;title&#39;,</span>
<span class="go">&#39;translate&#39;, &#39;upper&#39;, &#39;zfill&#39;]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>le module <a class="reference internal" href="#module-subprocess" title="subprocess: exécuter une commande shell, récupérer le code retour et la sortie"><code class="xref py py-mod docutils literal"><span class="pre">subprocess</span></code></a>, appels systèmes</li>
</ul>
<span class="target" id="module-subprocess"></span><dl class="function">
<dt>
<code class="descname">subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)¶</code></dt>
<dd></dd></dl>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">([</span><span class="s2">&quot;ls&quot;</span><span class="p">,</span> <span class="s2">&quot;-l&quot;</span><span class="p">])</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="s2">&quot;exit 1&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">1</span>
</pre></div>
</div>
<dl class="function">
<dt>
<code class="descname">subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)¶</code></dt>
<dd></dd></dl>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_output</span><span class="p">([</span><span class="s2">&quot;echo&quot;</span><span class="p">,</span> <span class="s2">&quot;Hello World!&quot;</span><span class="p">])</span>
<span class="go">&#39;Hello World!\n&#39;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_output</span><span class="p">(</span><span class="s2">&quot;exit 1&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">subprocess.CalledProcessError</span>: <span class="n">Command &#39;exit 1&#39; returned non-zero exit status 1</span>
</pre></div>
</div>
<ul class="simple">
<li>le module <a class="reference internal" href="#module-sys" title="sys: paramètres et fonctions systèmes"><code class="xref py py-mod docutils literal"><span class="pre">sys</span></code></a>, paramètres et fonctions systèmes</li>
</ul>
<span class="target" id="module-sys"></span><dl class="envvar">
<dt id="envvar-sys.argv">
<code class="descname">sys.argv</code><a class="headerlink" href="#envvar-sys.argv" title="Lien permanent vers cette définition"></a></dt>
<dd><p>la ligne de commande</p>
</dd></dl>
<dl class="function">
<dt id="sys.sys.exit">
<code class="descclassname">sys.</code><code class="descname">exit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.sys.exit" title="Lien permanent vers cette définition"></a></dt>
<dd><p>terminer un programme</p>
</dd></dl>
<dl class="envvar">
<dt id="envvar-sys.path">
<code class="descname">sys.path</code><a class="headerlink" href="#envvar-sys.path" title="Lien permanent vers cette définition"></a></dt>
<dd><p>ce quil y a dans le <span class="target" id="index-0"></span><a class="reference internal" href="settings.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal"><span class="pre">PYTHONPATH</span></code></a></p>
</dd></dl>
<span class="target" id="module-optparse"></span><ul class="simple">
<li>le module <a class="reference internal" href="#module-optparse" title="optparse: parsing de la ligne de commande"><code class="xref py py-mod docutils literal"><span class="pre">optparse</span></code></a> pour faire des outils ligne de commande</li>
</ul>
<p>module plus récent : argparse</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">Module docstring.</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">optparse</span>
<span class="k">def</span> <span class="nf">process_command_line</span><span class="p">(</span><span class="n">argv</span><span class="p">):</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd"> Return a 2-tuple: (settings object, args list).</span>
<span class="sd"> `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.</span>
<span class="sd"> &quot;&quot;&quot;</span>
<span class="k">if</span> <span class="n">argv</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">argv</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
<span class="c1"># initialize the parser object:</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">optparse</span><span class="o">.</span><span class="n">OptionParser</span><span class="p">(</span>
<span class="n">formatter</span><span class="o">=</span><span class="n">optparse</span><span class="o">.</span><span class="n">TitledHelpFormatter</span><span class="p">(</span><span class="n">width</span><span class="o">=</span><span class="mi">78</span><span class="p">),</span>
<span class="n">add_help_option</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
<span class="c1"># define options here:</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span> <span class="c1"># customized description; put --help last</span>
<span class="s1">&#39;-h&#39;</span><span class="p">,</span> <span class="s1">&#39;--help&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;help&#39;</span><span class="p">,</span>
<span class="n">help</span><span class="o">=</span><span class="s1">&#39;Show this help message and exit.&#39;</span><span class="p">)</span>
<span class="n">settings</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">argv</span><span class="p">)</span>
<span class="c1"># check number of arguments, verify values, etc.:</span>
<span class="k">if</span> <span class="n">args</span><span class="p">:</span>
<span class="n">parser</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;program takes no command-line arguments; &#39;</span>
<span class="s1">&#39;&quot;</span><span class="si">%s</span><span class="s1">&quot; ignored.&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">args</span><span class="p">,))</span>
<span class="c1"># further process settings &amp; args if necessary</span>
<span class="k">return</span> <span class="n">settings</span><span class="p">,</span> <span class="n">args</span>
<span class="k">def</span> <span class="nf">main</span><span class="p">(</span><span class="n">argv</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="n">settings</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">process_command_line</span><span class="p">(</span><span class="n">argv</span><span class="p">)</span>
<span class="c1"># application code here, like:</span>
<span class="c1"># run(settings, args)</span>
<span class="k">return</span> <span class="mi">0</span> <span class="c1"># success</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
<span class="n">status</span> <span class="o">=</span> <span class="n">main</span><span class="p">()</span>
<span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="n">status</span><span class="p">)</span>
</pre></div>
</div>
<ul class="simple">
<li>les modules de tests unitaires <a class="reference internal" href="#module-unittest" title="unittest: module de tests unitaires"><code class="xref py py-mod docutils literal"><span class="pre">unittest</span></code></a> et <code class="xref py py-mod docutils literal"><span class="pre">doctests</span></code></li>
</ul>
<span class="target" id="module-unittest"></span><span class="target" id="module-doctest"></span><ul class="simple">
<li>le module <code class="xref py py-mod docutils literal"><span class="pre">xml.etree</span></code> pour parser du xml</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">tree</span> <span class="o">=</span> <span class="n">xml</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;testFile.xml&quot;</span><span class="p">)</span>
<span class="n">rootElement</span> <span class="o">=</span> <span class="n">tree</span><span class="o">.</span><span class="n">getroot</span><span class="p">()</span>
<span class="n">bookList</span> <span class="o">=</span> <span class="n">rootElem</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;Books&quot;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">bookList</span> <span class="o">!=</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">for</span> <span class="n">book</span> <span class="ow">in</span> <span class="n">bookList</span><span class="p">:</span>
<span class="c1">#faire quelque chose avec les livres</span>
</pre></div>
</div>
<ul class="simple">
<li>le module <a class="reference internal" href="#module-urllib" title="urllib: parse des urls"><code class="xref py py-mod docutils literal"><span class="pre">urllib</span></code></a> pour parser les urls et les manipuler (<cite>urllib2</cite>)</li>
</ul>
<span class="target" id="module-urllib"></span><dl class="function">
<dt id="urllib.urllib.urlopen">
<code class="descclassname">urllib.</code><code class="descname">urlopen</code><span class="sig-paren">(</span><em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib.urllib.urlopen" title="Lien permanent vers cette définition"></a></dt>
<dd><p>lit une url distante</p>
</dd></dl>
<span class="target" id="module-time"></span><ul class="simple">
<li><a class="reference internal" href="#module-time" title="time: caculs de temps"><code class="xref py py-mod docutils literal"><span class="pre">time</span></code></a> pour la manipulation de temps</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">t1</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">clock</span><span class="p">()</span>
<span class="c1"># Do Stuff Here</span>
<span class="n">t2</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">clock</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">t2</span> <span class="o">-</span> <span class="n">t1</span>
</pre></div>
</div>
<p><strong>now</strong></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="n">now</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">localtime</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">())</span>
<span class="n">dateStr</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%A, %B </span><span class="si">%d</span><span class="s2">, %Y, %I:%M %p&quot;</span><span class="p">,</span> <span class="n">now</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">dateStr</span>
</pre></div>
</div>
<span class="target" id="module-getpass"></span><ul class="simple">
<li>le module <a class="reference internal" href="#module-getpass" title="getpass: recupération des mots de passe en ligne de commande"><code class="xref py py-mod docutils literal"><span class="pre">getpass</span></code></a> pour gérer les motes de passe</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">getpass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">getpass</span><span class="o">.</span><span class="n">getpass</span><span class="p">()</span>
<span class="go">Password:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>
<span class="go">&#39;toto&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<span class="target" id="module-shelve"></span><ul class="simple">
<li>linéarisation de données</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">shelve</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">shelve</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;database&quot;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="go">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">shelve</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;database&quot;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span>
<span class="go">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[</span><span class="s2">&quot;o&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">cl</span>
<span class="go">s.clear s.close</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">cl</span>
<span class="go">s.clear s.close</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<span class="target" id="module-abc"></span><ul class="simple">
<li>le module <a class="reference internal" href="#module-abc" title="abc: les abstract base classes"><code class="xref py py-mod docutils literal"><span class="pre">abc</span></code></a> pour faire des interfaces propres</li>
</ul>
<dl class="function">
<dt id="abc.abc.register">
<code class="descclassname">abc.</code><code class="descname">register</code><span class="sig-paren">(</span><em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#abc.abc.register" title="Lien permanent vers cette définition"></a></dt>
<dd><p>exemple</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="k">import</span> <span class="n">ABCMeta</span>
<span class="k">class</span> <span class="nc">MyABC</span><span class="p">:</span>
<span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
<span class="n">MyABC</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">tuple</span><span class="p">)</span>
<span class="k">assert</span> <span class="nb">issubclass</span><span class="p">(</span><span class="nb">tuple</span><span class="p">,</span> <span class="n">MyABC</span><span class="p">)</span>
<span class="k">assert</span> <span class="nb">isinstance</span><span class="p">((),</span> <span class="n">MyABC</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>
<span class="target" id="module-hotshot"></span><ul class="simple">
<li>le module <a class="reference internal" href="#module-hotshot" title="hotshot: benchmark"><code class="xref py py-mod docutils literal"><span class="pre">hotshot</span></code></a> benchmark</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">hotshot</span>
<span class="n">prof</span> <span class="o">=</span> <span class="n">hotshot</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="s1">&#39;toto.txt&#39;</span><span class="p">)</span>
<span class="n">prof</span><span class="o">.</span><span class="n">runcall</span><span class="p">(</span><span class="n">make_description</span><span class="p">)</span>
<span class="n">prof</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<ul class="simple">
<li>un exemple de librairie externe : <a class="reference internal" href="#module-IPy" title="IPy: traitement des ips en python &lt; python 3.3 remplacé par ipadress"><code class="xref py py-mod docutils literal"><span class="pre">IPy</span></code></a></li>
</ul>
<span class="target" id="module-IPy"></span><div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">sudo</span> <span class="n">apt</span><span class="o">-</span><span class="n">get</span> <span class="n">install</span> <span class="n">python</span><span class="o">-</span><span class="n">ipy</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPy</span> <span class="k">import</span> <span class="n">IP</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">ipy</span> <span class="o">=</span> <span class="n">IP</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">{0}</span><span class="s1">/</span><span class="si">{1}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">ip</span><span class="p">,</span> <span class="n">mask</span><span class="p">),</span> <span class="n">make_net</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="nb">print</span> <span class="s2">&quot;marche pas&quot;</span>
<span class="n">network</span> <span class="o">=</span> <span class="n">ipy</span><span class="o">.</span><span class="n">net</span><span class="p">()</span>
<span class="n">broadcast</span> <span class="o">=</span> <span class="n">ipy</span><span class="o">.</span><span class="n">broadcast</span><span class="p">()</span>
<span class="k">return</span> <span class="n">broadcast</span><span class="p">,</span> <span class="n">network</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="exercices.html" title="Liste des exercices"
>suivant</a> |</li>
<li class="right" >
<a href="DesignPatterns.html" title="Les design patterns"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,325 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Structures de contrôle et fonctions &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Tests unitaires et pile dappels" href="testsunitaires.html" />
<link rel="prev" title="Typage, types de base" href="type.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="testsunitaires.html" title="Tests unitaires et pile dappels"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="type.html" title="Typage, types de base"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="structures-de-controle-et-fonctions">
<h1>Structures de contrôle et fonctions<a class="headerlink" href="#structures-de-controle-et-fonctions" title="Lien permanent vers ce titre"></a></h1>
<ul class="simple">
<li>tests</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="s2">&quot;a&quot;</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="s2">&quot;a&quot;</span>
<span class="gp">...</span>
<span class="go">a</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="s2">&quot;&quot;</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="s2">&quot;hell&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="s2">&quot;un&quot;</span>
<span class="gp">... </span><span class="k">else</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="s2">&quot;deux&quot;</span>
<span class="gp">...</span>
<span class="go">deux</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">les types de base ont tous une valeur booléenne</p>
</div>
<ul class="simple">
<li>itérations</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="go">0</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">4</span>
<span class="go">5</span>
<span class="go">6</span>
<span class="go">7</span>
<span class="go">8</span>
<span class="go">9</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span>
<span class="go">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
</pre></div>
</div>
<ul class="simple">
<li>tant que</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="n">i</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">i</span>
<span class="gp">... </span> <span class="n">i</span> <span class="o">=</span> <span class="n">i</span> <span class="o">-</span><span class="mi">1</span>
<span class="gp">...</span>
<span class="go">10</span>
<span class="go">9</span>
<span class="go">8</span>
<span class="go">7</span>
<span class="go">6</span>
<span class="go">5</span>
<span class="go">4</span>
<span class="go">3</span>
<span class="go">2</span>
<span class="go">1</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="section" id="fonctions">
<h2>fonctions<a class="headerlink" href="#fonctions" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">blabla</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="sd">&quot;&quot;&quot;fonction qui printe&quot;&quot;&quot;</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">x</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>il ny a que des fonctions (et pas de procédures):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">ma_func</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="s2">&quot;écrit quelque chose dans un fichier&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ma_func</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ma_func</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">)</span>
<span class="go">None</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>est équivalent à :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">ma_func</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="s2">&quot;écrit quelque chose dans un fichier&quot;</span>
<span class="gp">... </span> <span class="k">return</span> <span class="kc">None</span>
</pre></div>
</div>
<ul>
<li><p class="first">arité dune fonction:</p>
<blockquote>
<div><ul class="simple">
<li>paramètre non nommé</li>
<li>paramètre nommé</li>
</ul>
</div></blockquote>
</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">ma_fonction</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="s2">&quot;arguments : &quot;</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="s2">&quot;argumments nommés&quot;</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ma_fonction</span><span class="p">(</span><span class="s2">&quot;toto&quot;</span><span class="p">,</span> <span class="s2">&quot;titi&quot;</span><span class="p">,</span> <span class="n">tutu</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">tata</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="go">arguments : (&#39;toto&#39;, &#39;titi&#39;)</span>
<span class="go">argumments nommés {&#39;tata&#39;: 3, &#39;tutu&#39;: 2}</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>signature dune fonction : ça peut renvoyer nimporte quoi (tout ce quon veut)</li>
</ul>
<p><a class="reference internal" href="#term-return"><span class="xref std std-term">return</span></a> ou <a class="reference internal" href="#term-yield"><span class="xref std std-term">yield</span></a> ?</p>
<dl class="glossary docutils">
<dt id="term-yield">yield</dt>
<dd>permet de renvoyer le résultat dune fonction en plusieurs étape
à laide dun générateur</dd>
<dt id="term-return">return</dt>
<dd>résultat dune fonction</dd>
</dl>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">ma_fonction</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">yield</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">ma_fonction</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="go">0</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">4</span>
<span class="go">5</span>
<span class="go">6</span>
<span class="go">7</span>
<span class="go">8</span>
<span class="go">9</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>espaces de nommage à lintérieur dune fonction :</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">toto</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="nb">vars</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">toto</span><span class="p">(</span><span class="s2">&quot;sdfsdf&quot;</span><span class="p">)</span>
<span class="go">{&#39;x&#39;: &#39;sdfsdf&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span><span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">A</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="s2">&quot;titi&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="s2">&quot;toto&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">vars</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">{&#39;a&#39;: &#39;titi&#39;, &#39;b&#39;: &#39;toto&#39;}</span>
</pre></div>
</div>
<p>puisque tout est objet en python, <code class="docutils literal"><span class="pre">vars(mon_objet)</span></code> est équivalent à
<code class="docutils literal"><span class="pre">mon_objet.__dict__</span></code></p>
<ul class="simple">
<li>générateurs et compréhension de liste</li>
</ul>
<p>les compréhensions de listes permettent de générer de nouvelles listes</p>
<p>exemple :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span> <span class="mi">2</span><span class="o">*</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>
<span class="go">[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="k">if</span> <span class="n">x</span><span class="o">&gt;</span><span class="mi">5</span><span class="p">]</span>
<span class="go">[6, 7, 8, 9]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">5</span><span class="p">)</span> <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">8</span><span class="p">)]</span>
<span class="go">[(2, 4), (2, 5), (2, 6), (2, 7), (3, 4), (3, 5), (3, 6), (3, 7), (4, 4), (4, 5), (4, 6), (4, 7)]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>les expressions générateurs</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span> <span class="o">=</span> <span class="p">(</span><span class="mi">2</span><span class="o">*</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expr</span>
<span class="go">&lt;generator object &lt;genexpr&gt; at 0x7ff9efa77cd0&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">expr</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">e</span>
<span class="gp">...</span>
<span class="go">0</span>
<span class="go">2</span>
<span class="go">4</span>
<span class="go">6</span>
<span class="go">8</span>
<span class="go">10</span>
<span class="go">12</span>
<span class="go">14</span>
<span class="go">16</span>
<span class="go">18</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="le-polymorphisme-parametrique">
<h2>le polymorphisme paramétrique<a class="headerlink" href="#le-polymorphisme-parametrique" title="Lien permanent vers ce titre"></a></h2>
<p>polymorphisme exemple de contexte :
la fonction print</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="mi">1</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s2">&quot;1&quot;</span>
<span class="go">1</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-0">
<p class="first admonition-title">À faire</p>
<p class="last"><code class="docutils literal"><span class="pre">print</span> <span class="pre">1</span></code> et <code class="docutils literal"><span class="pre">print</span> <span class="pre">&quot;1&quot;</span></code> renvoient le même résultat. Pourquoi ?</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="testsunitaires.html" title="Tests unitaires et pile dappels"
>suivant</a> |</li>
<li class="right" >
<a href="type.html" title="Typage, types de base"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,208 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tests unitaires et pile dappels &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Sphinx et docutils" href="docutils.html" />
<link rel="prev" title="Structures de contrôle et fonctions" href="structures.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="docutils.html" title="Sphinx et docutils"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="structures.html" title="Structures de contrôle et fonctions"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="tests-unitaires-et-pile-d-appels">
<h1>Tests unitaires et pile dappels<a class="headerlink" href="#tests-unitaires-et-pile-d-appels" title="Lien permanent vers ce titre"></a></h1>
<p>Les tests automatiques sont un complément à la déclaration des types.</p>
<p>que tester, quoi tester ?</p>
<ul class="simple">
<li>que les composants interagissent bien entre eux</li>
<li>que les unités (fonctions, objets…) réagissent bien à une entrée spécifique</li>
<li>que le code se comporte de la manière attendue dans des environnements différents
(systèmes dexploitation, etc…)</li>
</ul>
<p>les types de tests :</p>
<ul class="simple">
<li>tests unitaires</li>
<li>tests fonctionnels</li>
<li>tests dacceptation</li>
<li>tests dintégration</li>
</ul>
<p>Quel outil utiliser ?</p>
<ul class="simple">
<li>la <a class="reference internal" href="stdlib.html"><span class="doc">La librairie standard</span></a> propose le module <a class="reference internal" href="stdlib.html#module-unittest" title="unittest: module de tests unitaires"><code class="xref py py-mod docutils literal"><span class="pre">unittest</span></code></a> et unittest2.</li>
</ul>
<span class="target" id="module-py.test"></span><ul class="simple">
<li><a class="reference internal" href="#module-py.test" title="py.test: outil de test unitaires de la pylib"><code class="xref py py-mod docutils literal"><span class="pre">py.test</span></code></a> est <strong>le plus simple</strong> (plus simple que unittest)</li>
</ul>
<p><a class="reference external" href="http://pytest.org/latest/">http://pytest.org/latest/</a></p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test_simple</span><span class="p">():</span>
<span class="s2">&quot;test si ma_fontion renvoie bien 3&quot;</span>
<span class="k">assert</span> <span class="n">ma_fontion</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">3</span>
</pre></div>
</div>
<ul class="simple">
<li><cite>py.test</cite> utilise <cite>assert</cite> et <cite>raises</cite></li>
<li><cite>unittest</cite> necessite de faire sytématiquement une classe, puis <cite>assertEqual()</cite></li>
<li><a class="reference internal" href="stdlib.html#module-doctest" title="doctest: module de tests unitaires basé sur les docstrings"><code class="xref py py-mod docutils literal"><span class="pre">doctest</span></code></a> est plus simple mais charge trop les docstrings</li>
</ul>
<div class="admonition-todo admonition" id="index-0">
<p class="first admonition-title">À faire</p>
<p class="last">écrire un test unitaire avec <cite>py.test</cite> pour la fonction suivante</p>
</div>
<ul class="simple">
<li>installer le paquet <cite>python-pytest</cite></li>
<li>écrire un fichier avec une fonction dedans</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">double</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="mi">2</span>
</pre></div>
</div>
<ul class="simple">
<li>écrire un fichier commençant par <cite>test_</cite> qui teste les fonctions du fichier</li>
</ul>
<div class="section" id="options-utiles-dans-py-test">
<h2>options utiles dans <cite>py.test</cite><a class="headerlink" href="#options-utiles-dans-py-test" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">py</span><span class="o">.</span><span class="n">test</span> <span class="o">--</span><span class="n">tb</span><span class="o">=</span><span class="n">no</span>
<span class="n">py</span><span class="o">.</span><span class="n">test</span> <span class="o">--</span><span class="n">tb</span><span class="o">=</span><span class="n">short</span>
<span class="n">py</span><span class="o">.</span><span class="n">test</span> <span class="o">-</span><span class="n">x</span> <span class="p">(</span><span class="n">dernière</span> <span class="n">erreur</span><span class="p">)</span>
<span class="n">py</span><span class="o">.</span><span class="n">test</span> <span class="o">-</span><span class="n">s</span> <span class="p">(</span><span class="n">c</span><span class="s1">&#39;est comme nocapture en fait)</span>
<span class="n">py</span><span class="o">.</span><span class="n">test</span> <span class="o">-</span><span class="n">x</span> <span class="o">--</span><span class="n">nocapture</span> <span class="o">--</span><span class="n">pdb</span>
<span class="n">py</span><span class="o">.</span><span class="n">test</span> <span class="o">-</span><span class="n">xl</span> <span class="o">--</span><span class="n">pdb</span>
<span class="n">py</span><span class="o">.</span><span class="n">test</span> <span class="o">-</span><span class="n">k</span> <span class="n">test_simple</span>
</pre></div>
</div>
<p>utiliser le module <a class="reference internal" href="#module-pdb" title="pdb: debugger de la lib standard"><code class="xref py py-mod docutils literal"><span class="pre">pdb</span></code></a></p>
<span class="target" id="module-pdb"></span><div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pdb</span>
<span class="n">pdb</span><span class="o">.</span><span class="n">set_trace</span><span class="p">()</span>
</pre></div>
</div>
<p>depuis py.test :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pytest</span>
<span class="k">def</span> <span class="nf">test_function</span><span class="p">():</span>
<span class="o">...</span>
<span class="n">pytest</span><span class="o">.</span><span class="n">set_trace</span><span class="p">()</span> <span class="c1"># invoke PDB debugger and tracing</span>
</pre></div>
</div>
<p>Remarquons que <a class="reference internal" href="#module-pdb" title="pdb: debugger de la lib standard"><code class="xref py py-mod docutils literal"><span class="pre">pdb</span></code></a> utilise le module <a class="reference internal" href="prompt.html#module-cmd" title="cmd: interpréteur ligne de commande"><code class="xref py py-mod docutils literal"><span class="pre">cmd</span></code></a>, voir <a class="reference internal" href="prompt.html#cmdlabel"><span class="std std-ref">le module cmd et les interpréteurs</span></a> quon a déjà vu précedemment</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">Pdb</span><span class="p">)</span> <span class="n">h</span>
<span class="n">Documented</span> <span class="n">commands</span> <span class="p">(</span><span class="nb">type</span> <span class="n">help</span> <span class="o">&lt;</span><span class="n">topic</span><span class="o">&gt;</span><span class="p">):</span>
<span class="o">========================================</span>
<span class="n">EOF</span> <span class="n">bt</span> <span class="n">cont</span> <span class="n">enable</span> <span class="n">jump</span> <span class="n">pp</span> <span class="n">run</span> <span class="n">unt</span>
<span class="n">a</span> <span class="n">c</span> <span class="k">continue</span> <span class="n">exit</span> <span class="n">l</span> <span class="n">q</span> <span class="n">s</span> <span class="n">until</span>
<span class="n">alias</span> <span class="n">cl</span> <span class="n">d</span> <span class="n">h</span> <span class="nb">list</span> <span class="n">quit</span> <span class="n">step</span> <span class="n">up</span>
<span class="n">args</span> <span class="n">clear</span> <span class="n">debug</span> <span class="n">help</span> <span class="n">n</span> <span class="n">r</span> <span class="n">tbreak</span> <span class="n">w</span>
<span class="n">b</span> <span class="n">commands</span> <span class="n">disable</span> <span class="n">ignore</span> <span class="nb">next</span> <span class="n">restart</span> <span class="n">u</span> <span class="n">whatis</span>
<span class="k">break</span> <span class="n">condition</span> <span class="n">down</span> <span class="n">j</span> <span class="n">p</span> <span class="k">return</span> <span class="n">unalias</span> <span class="n">where</span>
<span class="n">Miscellaneous</span> <span class="n">help</span> <span class="n">topics</span><span class="p">:</span>
<span class="o">==========================</span>
<span class="n">exec</span> <span class="n">pdb</span>
<span class="n">Undocumented</span> <span class="n">commands</span><span class="p">:</span>
<span class="o">======================</span>
<span class="n">retval</span> <span class="n">rv</span>
<span class="p">(</span><span class="n">Pdb</span><span class="p">)</span>
</pre></div>
</div>
<p>last but not least :</p>
<p>utiliser pylint ou pychecker</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">apt</span><span class="o">-</span><span class="n">get</span> <span class="n">install</span> <span class="n">pylint</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="docutils.html" title="Sphinx et docutils"
>suivant</a> |</li>
<li class="right" >
<a href="structures.html" title="Structures de contrôle et fonctions"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>

View File

@ -0,0 +1,810 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Typage, types de base &#8212; Documentation Formation Python 1</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/translations.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Recherche" href="search.html" />
<link rel="next" title="Structures de contrôle et fonctions" href="structures.html" />
<link rel="prev" title="Mettre en place son environnement de travail" href="settings.html" />
</head>
<body>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<table><tr><td>
<img src="_static/sphinx.png" alt="logo" />
</td><td>
<h1>&nbsp; &nbsp; Programmation python</h1>
</td></tr></table>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="structures.html" title="Structures de contrôle et fonctions"
accesskey="N">suivant</a> |</li>
<li class="right" >
<a href="settings.html" title="Mettre en place son environnement de travail"
accesskey="P">précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<p>&nbsp;</p>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="typage-types-de-base">
<h1>Typage, types de base<a class="headerlink" href="#typage-types-de-base" title="Lien permanent vers ce titre"></a></h1>
<p>python est un langage dynamiquement typé. quest-ce que cela signifie ?</p>
<ul class="simple">
<li>pas de déclaration des types (attention différent de linférence de types): les variables nont pas
de type fixé, ce qui signifie que le type est fixé au moment de laffectation
(pendant le rutime).</li>
<li>pas de déclaration des variables (une variable est créée au moyen de la première
affectation).</li>
</ul>
<div class="admonition-todo admonition" id="index-0">
<p class="first admonition-title">À faire</p>
<p class="last">créer une variable</p>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">3</span>
</pre></div>
</div>
<ul class="simple">
<li>ouvrir linterpréteur python</li>
<li>dans la console créer un objet de type integer, float, string, liste, dictionnaire</li>
<li>vérifier les types à laide de la fonction</li>
<li>vérifier que en python tout est objet</li>
<li>type de base et types conteneurs</li>
<li>types mutables et types immutables</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">5</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="p">[</span><span class="n">l</span><span class="p">,</span> <span class="s1">&#39;e&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>
<span class="go">[[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;], &#39;e&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="s1">&#39;j&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>
<span class="go">[[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;], &#39;e&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span>
<span class="go">[&#39;i&#39;, &#39;j&#39;]</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-1">
<p class="first admonition-title">À faire</p>
<p class="last">jouer avec les types</p>
</div>
<ul class="simple">
<li>linterpréteur python comme calculette, les opérations numériques</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span><span class="mi">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">&gt;</span> <span class="n">y</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">==</span> <span class="n">y</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">!=</span> <span class="n">y</span>
<span class="go">True</span>
</pre></div>
</div>
<ul class="simple">
<li>linterpréteur pour manipuler les strings</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;bla bla&quot;</span>
<span class="go">&#39;bla bla&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;bla bla&#39;</span>
<span class="go">&#39;bla bla&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot; &#39;bli bli&#39; &quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span>
<span class="go">&quot; &#39;bli bli&#39; &quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot; sdfsdf &quot;bla bla&quot; sdfsdf&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span>
<span class="go">&#39; sdfsdf &quot;bla bla&quot; sdfsdf&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;bla bla&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="s2">&quot;hu hu&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">+</span> <span class="n">m</span>
<span class="go">&#39;bla blahu hu&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">*</span> <span class="mi">3</span>
<span class="go">&#39;hu huhu huhu hu&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="go">5</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span>
<span class="go">&#39;h&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">3</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span>
<span class="go">&#39;hu&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;ssdfsdf </span><span class="si">{0}</span><span class="s2"> sdfsdfsdf </span><span class="si">{1}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;blah&quot;</span><span class="p">,</span> <span class="s2">&quot;blih&quot;</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">=</span> <span class="s1">&#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getnewargs__&#39;, &#39;__getslice__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;_formatter_field_name_split&#39;, &#39;_formatter_parser&#39;, &#39;capitalize&#39;, &#39;center&#39;, &#39;count&#39;, &#39;decode&#39;, &#39;encode&#39;, &#39;endswith&#39;, &#39;expandtabs&#39;, &#39;find&#39;, &#39;format&#39;, &#39;index&#39;, &#39;isalnum&#39;, &#39;isalpha&#39;, &#39;isdigit&#39;, &#39;islower&#39;, &#39;isspace&#39;, &#39;istitle&#39;, &#39;isupper&#39;, &#39;join&#39;, &#39;ljust&#39;, &#39;lower&#39;, &#39;lstrip&#39;, &#39;partition&#39;, &#39;replace&#39;, &#39;rfind&#39;, &#39;rindex&#39;, &#39;rjust&#39;, &#39;rpartition&#39;, &#39;rsplit&#39;, &#39;rstrip&#39;, &#39;split&#39;, &#39;splitlines&#39;, &#39;startswith&#39;, &#39;strip&#39;, &#39;swapcase&#39;, &#39;title&#39;, &#39;translate&#39;, &#39;upper&#39;, &#39;zfill&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="s2">&quot;abc&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;-&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">l</span><span class="p">)</span>
<span class="go">&#39;a-b-c&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-2">
<p class="first admonition-title">À faire</p>
<p class="last">lower(), upper(), strip(), title()</p>
</div>
<p>index(), find(), replace()</p>
<ul class="simple">
<li>le module <a class="reference internal" href="#module-regexp" title="regexp: expression régulières"><code class="xref py py-mod docutils literal"><span class="pre">regexp</span></code></a></li>
</ul>
<span class="target" id="module-regexp"></span><div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;sdf dfdfdf blah bla df&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\w*&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
<span class="go">[&#39;sdf&#39;, &#39;&#39;, &#39;dfdfdf&#39;, &#39;&#39;, &#39;blah&#39;, &#39;&#39;, &#39;bla&#39;, &#39;&#39;, &#39;df&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;df*&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
<span class="go">[&#39;df&#39;, &#39;df&#39;, &#39;df&#39;, &#39;df&#39;, &#39;df&#39;]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="section" id="unicode">
<h2>unicode<a class="headerlink" href="#unicode" title="Lien permanent vers ce titre"></a></h2>
<p>En python 2.X : deux types : <code class="docutils literal"><span class="pre">str</span></code> et <code class="docutils literal"><span class="pre">unicode</span></code> (en python 3 ces types sont unifiés)</p>
<p>on peut facilement tomber sur des erreurs unicode:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="ne">UnicodeEncodeError</span><span class="p">:</span> <span class="s1">&#39;ascii&#39;</span> <span class="n">codec</span> <span class="n">can</span><span class="s1">&#39;t encode character u&#39;</span>\<span class="n">xe9</span><span class="s1">&#39; in position 0:</span>
<span class="n">ordinal</span> <span class="ow">not</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">128</span><span class="p">)</span>
</pre></div>
</div>
<ul class="simple">
<li>lencodage (unicode):</li>
</ul>
<p>on part dun objet unicode :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="sa">u</span><span class="s2">&quot;éèà bla&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span>
<span class="go">u&#39;\xe9\xe8\xe0 bla&#39;</span>
</pre></div>
</div>
<p>on le transforme en string utf-8 :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>
<span class="go">&#39;\xc3\xa9\xc3\xa8\xc3\xa0 bla&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>
<span class="go">éèà bla</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>on peut partir dune string en utf-8, puis:</p>
<p>manips importantes de traitement unicode (si on nest pas en python 3)</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="sa">u</span><span class="s2">&quot;ésdsfè&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span>
<span class="go">u&#39;\xe9sdsf\xe8&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">u</span>
<span class="go">ésdsfè</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">UnicodeEncodeError</span>: <span class="n">&#39;ascii&#39; codec can&#39;t encode character u&#39;\xe9&#39; in position 0:</span>
<span class="go">ordinal not in range(128)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>
<span class="go">&#39;\xc3\xa9sdsf\xc3\xa8&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&lt;type &#39;str&#39;&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Il faut utiliser <code class="docutils literal"><span class="pre">.encode()</span></code>, et pas <code class="docutils literal"><span class="pre">.decode()</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">==</span> <span class="n">unicode</span> <span class="c1">#types.UnicodeType:</span>
<span class="n">bla</span> <span class="n">bla</span>
<span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">==</span> <span class="nb">str</span><span class="p">:</span>
<span class="n">rien</span> <span class="n">à</span> <span class="n">faire</span>
</pre></div>
</div>
<p>manipulations diverses :</p>
<ul class="simple">
<li>enlever les accents</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">unicodedata</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="sa">u</span><span class="s2">&quot;un été même pas chaud&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">unicodedata</span> <span class="k">as</span> <span class="nn">U</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s2</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">U</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="s1">&#39;NFD&#39;</span><span class="p">,</span> <span class="n">x</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s2</span>
<span class="go">u&#39;un ete meme pas chaud&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>enlever la ponctuation</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rgx</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;[</span><span class="si">%s</span><span class="s1">]&#39;</span> <span class="o">%</span> <span class="n">string</span><span class="o">.</span><span class="n">punctuation</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">string</span><span class="o">.</span><span class="n">punctuation</span>
<span class="go">&#39;!&quot;#$%&amp;\&#39;()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="tuples-listes-dictionnaires">
<h2>tuples, listes, dictionnaires<a class="headerlink" href="#tuples-listes-dictionnaires" title="Lien permanent vers ce titre"></a></h2>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span><span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">:</span><span class="mi">4</span><span class="p">}</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;e&#39;</span><span class="p">,</span><span class="s1">&#39;p&#39;</span><span class="p">,</span><span class="s1">&#39;q&#39;</span><span class="p">,</span><span class="s1">&#39;t&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">&#39;t&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span>
<span class="go">[&#39;e&#39;, &#39;p&#39;, &#39;q&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span>
<span class="go">[&#39;e&#39;, &#39;p&#39;, &#39;q&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;p&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span>
<span class="go">[&#39;e&#39;, &#39;q&#39;]</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="go">exercice</span>
<span class="go">-------------</span>
</pre></div>
</div>
<p>écrire la string «&nbsp;1-2-3-4-5-6-7-8-9&nbsp;» programmatiquement</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">l</span><span class="p">]</span>
<span class="go">[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l2</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">l</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">l2</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">))</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l2</span>
<span class="go">[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;]</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">9</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l2</span> <span class="o">=</span> <span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">l</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;-&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">l2</span><span class="p">)</span>
<span class="go">&#39;1-2-3-4-5-6-7-8&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">=</span> <span class="s2">&quot;-&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l2</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l2</span>
<span class="go">[&#39;1&#39;, &#39;2&#39;, &#39;sdfsdf&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">+</span> <span class="n">l2</span>
<span class="go">[1, 2, 3, 4, 5, 6, 7, 8, &#39;1&#39;, &#39;2&#39;, &#39;sdfsdf&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">l2</span><span class="p">)</span>
<span class="nc">KeyboardInterrupt</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="nb">list</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span>
<span class="go">&lt;type &#39;list&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">()</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="go">[0, 1]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">tuple</span>
<span class="go">&lt;type &#39;tuple&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span>
<span class="go">(1, 2, 3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">[1, 2, 3]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span>
<span class="go">(1, 2, 3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">&lt;type &#39;tuple&#39;&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">utiliser get plutôt que laccès par items lorsque lon nest pas sûr</p>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;toto&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;toto&#39;</span><span class="p">]</span> <span class="o">=</span><span class="s1">&#39;titi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;toto&#39;</span><span class="p">)</span>
<span class="go">&#39;titi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">d</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;toto&#39;</span><span class="p">)</span>
<span class="go">titi</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">d</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;to&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;tot&#39;</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">KeyError</span>: <span class="n">&#39;tot&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="nc">KeyboardInterrupt</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">=</span><span class="nb">dict</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">23</span><span class="p">,</span><span class="n">b</span><span class="o">=</span><span class="mi">45</span><span class="p">,</span><span class="n">c</span><span class="o">=</span><span class="mi">67</span><span class="p">,</span><span class="n">d</span><span class="o">=</span><span class="mi">89</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">{&#39;a&#39;: 23, &#39;c&#39;: 67, &#39;b&#39;: 45, &#39;d&#39;: 89}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">=</span><span class="nb">dict</span><span class="o">.</span><span class="n">fromkeys</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">),</span> <span class="s1">&#39;ho&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span>
<span class="go">{0: &#39;ho&#39;, 1: &#39;ho&#39;, 2: &#39;ho&#39;, 3: &#39;ho&#39;}</span>
</pre></div>
</div>
<p># and a new method to fetch-and-remove an item, by key:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="go">67</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">{&#39;a&#39;: 23, &#39;b&#39;: 45, &#39;d&#39;: 89}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">KeyError</span>: <span class="n">&#39;z&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">,</span> <span class="mi">55</span><span class="p">)</span>
<span class="go">55</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="s1">&#39;ciao&#39;</span><span class="p">):</span> <span class="nb">print</span> <span class="n">x</span>
<span class="gp">...</span>
<span class="go">(0, &#39;c&#39;)</span>
<span class="go">(1, &#39;i&#39;)</span>
<span class="go">(2, &#39;a&#39;)</span>
<span class="go">(3, &#39;o&#39;)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<span class="target" id="module-collections"></span><ul class="simple">
<li>le module <a class="reference internal" href="#module-collections" title="collections: autres types de données"><code class="xref py py-mod docutils literal"><span class="pre">collections</span></code></a> :</li>
<li><code class="docutils literal"><span class="pre">OrderedDict</span></code>, <code class="docutils literal"><span class="pre">defaultdict</span></code></li>
</ul>
<p>remarques sur les tuples</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span><span class="p">,</span>
<span class="go">(1,)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1</span><span class="p">,)</span>
<span class="go">(1,)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">()</span>
<span class="go">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">tuple</span><span class="p">()</span>
<span class="go">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span>
<span class="go">(1,)</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-3">
<p class="first admonition-title">À faire</p>
<p class="last">addition de listes, append, tranches, tri de listes</p>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">remove_duplicates</span><span class="p">(</span><span class="n">lst</span><span class="p">):</span>
<span class="o">...</span>
<span class="n">l</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="s2">&quot;hello&quot;</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="s2">&quot;world&quot;</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">7</span><span class="p">]</span>
<span class="n">remove_duplicates</span><span class="p">(</span><span class="n">l</span><span class="p">)</span>
<span class="k">assert</span> <span class="n">l</span> <span class="o">==</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="s2">&quot;hello&quot;</span><span class="p">,</span> <span class="s2">&quot;world&quot;</span><span class="p">]</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-4">
<p class="first admonition-title">À faire</p>
<p class="last">defaultdict, get (avec une valeur par défaut)</p>
</div>
<ul class="simple">
<li>tri de liste personnalisé :</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Sorter</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">sort</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">):</span>
<span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="nb">list</span><span class="p">)):</span>
<span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">compareItems</span><span class="p">(</span><span class="nb">list</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="nb">list</span><span class="p">[</span><span class="n">j</span><span class="p">]):</span>
<span class="nb">list</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="nb">list</span><span class="p">[</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="nb">list</span><span class="p">[</span><span class="n">j</span><span class="p">],</span> <span class="nb">list</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">getName</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;Trieur de liste&quot;</span>
<span class="k">def</span> <span class="nf">getDescription</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">NotImplementedError</span>
<span class="k">def</span> <span class="nf">compareItems</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">item1</span><span class="p">,</span> <span class="n">item2</span><span class="p">):</span>
<span class="k">raise</span> <span class="ne">NotImplementedError</span>
<span class="k">class</span> <span class="nc">AscendantSorter</span><span class="p">(</span><span class="n">Sorter</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">compareItems</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">item1</span><span class="p">,</span> <span class="n">item2</span><span class="p">):</span>
<span class="k">return</span> <span class="n">item1</span> <span class="o">&gt;=</span> <span class="n">item2</span>
<span class="k">def</span> <span class="nf">getDescription</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;Tri par ordre normal&quot;</span>
<span class="k">def</span> <span class="nf">getName</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;Ascendant&quot;</span>
<span class="k">class</span> <span class="nc">DescendantSorter</span><span class="p">(</span><span class="n">Sorter</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">compareItems</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">item1</span><span class="p">,</span> <span class="n">item2</span><span class="p">):</span>
<span class="k">return</span> <span class="n">item1</span> <span class="o">&lt;=</span> <span class="n">item2</span>
<span class="k">def</span> <span class="nf">getDescription</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">&quot;Tri par ordre inverse&quot;</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
<span class="nb">list</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;e&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;z&#39;</span><span class="p">]</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">AscendantSorter</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="nb">print</span> <span class="nb">list</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">DescendantSorter</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="nb">print</span> <span class="nb">list</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;a&#39;</span> <span class="ow">in</span> <span class="n">d</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="go">2</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">l</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">d</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="go">a</span>
<span class="go">c</span>
<span class="go">b</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span> <span class="n">key</span><span class="p">,</span> <span class="s2">&quot; : &quot;</span><span class="p">,</span> <span class="n">value</span>
<span class="gp">...</span>
<span class="go">a : 2</span>
<span class="go">c : 4</span>
<span class="go">b : 3</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition-todo admonition" id="index-5">
<p class="first admonition-title">À faire</p>
<p class="last">linterpréteur python pour lintrospection des objets</p>
</div>
<p>en python, <strong>pas besoin de déclaration de type</strong>. Quest-ce que ça veut dire ?</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&lt;type &#39;int&#39;&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__class__&#39;, &#39;__cmp__&#39;, &#39;__coerce__&#39;,</span>
<span class="go">&#39;__delattr__&#39;, &#39;__div__&#39;, &#39;__divmod__&#39;, &#39;__doc__&#39;, &#39;__float__&#39;, &#39;__floordiv__&#39;,</span>
<span class="go">&#39;__format__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__hash__&#39;, &#39;__hex__&#39;,</span>
<span class="go">&#39;__index__&#39;, &#39;__init__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__long__&#39;, &#39;__lshift__&#39;,</span>
<span class="go">&#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__nonzero__&#39;, &#39;__oct__&#39;, &#39;__or__&#39;,</span>
<span class="go">&#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rdiv__&#39;, &#39;__rdivmod__&#39;,</span>
<span class="go">&#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloordiv__&#39;, &#39;__rlshift__&#39;,</span>
<span class="go">&#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;,</span>
<span class="go">&#39;__rsub__&#39;, &#39;__rtruediv__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;,</span>
<span class="go">&#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truediv__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;,</span>
<span class="go">&#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;]</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">&lt;type &#39;int&#39;&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<ul class="simple">
<li>Le type set</li>
</ul>
<p>Set</p>
<blockquote>
<div>collection non ordonnées déléments uniques</div></blockquote>
<ul class="simple">
<li>le type set immutable et le type set mutable.</li>
<li>un ensemble peut être étendu ou bien seulement englobé</li>
</ul>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">Manipulations</span> <span class="n">non</span> <span class="n">supportées</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="p">[</span><span class="s2">&quot;a&quot;</span><span class="p">]</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
<span class="ne">TypeError</span><span class="p">:</span> <span class="n">unsubscriptable</span> <span class="nb">object</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">)</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
<span class="ne">AttributeError</span><span class="p">:</span> <span class="s1">&#39;Set&#39;</span> <span class="nb">object</span> <span class="n">has</span> <span class="n">no</span> <span class="n">attribute</span> <span class="s1">&#39;append&#39;</span>
</pre></div>
</div>
<p>Création</p>
<p>Ensemble vide :</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s2">&quot;toto&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([&#39;t&#39;, &#39;o&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;a&quot;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span><span class="s2">&quot;b&quot;</span><span class="p">:</span><span class="mi">2</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span>
<span class="go">Set([&#39;a&#39;, &#39;b&#39;])</span>
</pre></div>
</div>
<p>Appartenance et définition en extension</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="n">i</span>
<span class="kc">True</span>
<span class="o">&gt;&gt;&gt;</span> <span class="nb">len</span><span class="p">(</span><span class="n">h</span><span class="p">)</span>
<span class="mi">4</span>
<span class="o">&gt;&gt;&gt;</span> <span class="k">for</span> <span class="n">u</span> <span class="ow">in</span> <span class="n">h</span><span class="p">:</span>
<span class="o">...</span> <span class="nb">print</span> <span class="n">u</span>
<span class="o">...</span>
<span class="n">a</span>
<span class="n">b</span>
<span class="n">t</span>
<span class="n">o</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
<span class="o">...</span> <span class="n">e</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="o">...</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s2">&quot;b&quot;</span><span class="p">,</span> <span class="s2">&quot;c&quot;</span><span class="p">)</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
<span class="ne">TypeError</span><span class="p">:</span> <span class="n">add</span><span class="p">()</span> <span class="n">takes</span> <span class="n">exactly</span> <span class="mi">2</span> <span class="n">arguments</span> <span class="p">(</span><span class="mi">3</span> <span class="n">given</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
<span class="o">...</span> <span class="n">e</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="o">...</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span>
<span class="c1"># Suppression :</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">f</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">f</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">f</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>Opérations sur les ensembles</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">issuperset</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">&amp;</span><span class="n">lt</span><span class="p">;</span> <span class="n">e</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">&amp;</span><span class="n">gt</span><span class="p">;</span> <span class="n">e</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([&#39;a&#39;, 0, 2, 3, 4, 1, ImmutableSet([&#39;p&#39;])])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="go">Set([&#39;a&#39;, 0, 2, 3, 4, 1, ImmutableSet([&#39;p&#39;])])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([&#39;a&#39;, 0, 2, 4, 1, ImmutableSet([&#39;p&#39;])])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">0</span> <span class="ow">in</span> <span class="n">e</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">&#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([0, 2, 4, 1, ImmutableSet([&#39;p&#39;])])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">discard</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([2, 1, ImmutableSet([&#39;p&#39;])])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">discard</span><span class="p">(</span><span class="s2">&quot;p&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([2, 1, ImmutableSet([&#39;p&#39;])])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">discard</span><span class="p">(</span><span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">(</span><span class="s2">&quot;p&quot;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([2, 1])</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">-=</span> <span class="n">f</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span>
<span class="go">Set([&#39;a&#39;, 2, 3, 4, 1])</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span>
<span class="go">Set([])</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="go"># copy</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h</span> <span class="o">==</span> <span class="n">e</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h</span> <span class="o">!=</span> <span class="n">e</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="n">h</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span>
<span class="go">Set([&#39;a&#39;, &#39;b&#39;, &#39;t&#39;, &#39;o&#39;])</span>
</pre></div>
</div>
<p>Opérations ensemblistes</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="c1">#Pas d&#39;opération &quot;+&quot; :</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">h</span> <span class="o">=</span> <span class="n">e</span> <span class="o">+</span> <span class="n">f</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
<span class="ne">TypeError</span><span class="p">:</span> <span class="n">unsupported</span> <span class="n">operand</span> <span class="nb">type</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="o">+</span><span class="p">:</span> <span class="s1">&#39;Set&#39;</span> <span class="ow">and</span> <span class="s1">&#39;Set&#39;</span>
<span class="c1">#La réunion :</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">g</span> <span class="o">=</span> <span class="n">e</span> <span class="ow">or</span> <span class="n">f</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">g</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;t&#39;</span><span class="p">,</span> <span class="s1">&#39;o&#39;</span><span class="p">])</span>
<span class="n">autre</span> <span class="n">notation</span> <span class="p">:</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">h</span> <span class="o">|</span> <span class="n">e</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;t&#39;</span><span class="p">,</span> <span class="s1">&#39;o&#39;</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">h</span> <span class="o">&amp;</span> <span class="n">e</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;t&#39;</span><span class="p">,</span> <span class="s1">&#39;o&#39;</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span>
<span class="n">Le</span> <span class="n">complémentaire</span> <span class="p">:</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">h</span> <span class="o">=</span> <span class="n">e</span> <span class="o">^</span> <span class="n">f</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">h</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;t&#39;</span><span class="p">,</span> <span class="s1">&#39;o&#39;</span><span class="p">])</span>
<span class="n">La</span> <span class="n">différence</span> <span class="p">:</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">i</span> <span class="o">=</span> <span class="n">h</span> <span class="o">-</span> <span class="n">e</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">i</span>
<span class="n">L</span><span class="s1">&#39;intersection, la réunion, le complémentaire :</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">f</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">f</span> <span class="o">&amp;</span> <span class="n">e</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">f</span> <span class="o">|</span> <span class="n">e</span>
<span class="n">Set</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">f</span> <span class="o">^</span> <span class="n">e</span>
<span class="n">Set</span><span class="p">([</span><span class="mi">0</span><span class="p">])</span>
</pre></div>
</div>
</div>
<div class="section" id="difference-entre-type-et-isinstance">
<h2>différence entre type et isinstance<a class="headerlink" href="#difference-entre-type-et-isinstance" title="Lien permanent vers ce titre"></a></h2>
<p><code class="docutils literal"><span class="pre">type()</span></code> ne gère pas lhéritage alors que <code class="docutils literal"><span class="pre">isinstance()</span></code> si:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="go"> def __init__(self):</span>
<span class="go"> pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="o">==</span> <span class="n">MyClass</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="o">==</span> <span class="nb">object</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">MyClass</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="nb">object</span><span class="p">)</span>
<span class="go">True</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Dans la <strong>PEP 8</strong>, Guido demande explicitement dutiliser isinstance et non type</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>citation :</p>
<p>Object type comparisons should always use isinstance() instead
of comparing types directly.</p>
<blockquote class="last">
<div><p>Yes: if isinstance(obj, int):</p>
<p>No: if type(obj) is int:</p>
</div></blockquote>
</div>
<div class="section" id="inference-de-type">
<h3>inférence de type<a class="headerlink" href="#inference-de-type" title="Lien permanent vers ce titre"></a></h3>
<div class="admonition-todo admonition" id="index-6">
<p class="first admonition-title">À faire</p>
<p class="last">coercion, typage dynamique, inférence de type</p>
</div>
<p>exemple:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">addition_forte</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">int</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="nb">int</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">addition_faible</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
</pre></div>
</div>
<p>dans <code class="docutils literal"><span class="pre">addition_faible</span></code>, il ny a pas de casting de type, on nessaye pas
de transformer ça en un type donné, cest-à-dire que si <code class="docutils literal"><span class="pre">x</span></code> et <code class="docutils literal"><span class="pre">y</span></code> sont
compatible, ça marche. Le typage est fort, on demande des types</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">addition_faible</span><span class="p">(</span><span class="s2">&quot;1&quot;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">TypeError: cannot concatenate &#39;str&#39; and &#39;int&#39; objects</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">addition_forte</span><span class="p">(</span><span class="s2">&quot;1&quot;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">TypeError: cannot concatenate &#39;str&#39; and &#39;int&#39; objects</span>
</pre></div>
</div>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">addition_faible</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">,</span> <span class="s2">&quot;b&quot;</span><span class="p">)</span>
<span class="go">5</span>
</pre></div>
</div>
<p>Remarquons que <code class="docutils literal"><span class="pre">addition_faible</span></code> renvoie forcément un type <code class="docutils literal"><span class="pre">int</span></code> tandis
que <code class="docutils literal"><span class="pre">addition_forte</span></code> peut renvoyer un autre type, ceci est dû au
polymorphisme paramétrique.</p>
<div class="admonition-todo admonition" id="index-7">
<p class="first admonition-title">À faire</p>
<p class="last">en python un type et une classe, cest la même chose</p>
</div>
<div class="admonition-todo admonition" id="index-8">
<p class="first admonition-title">À faire</p>
<p class="last">«&nbsp;duck typing&nbsp;» en python</p>
</div>
<ul class="simple">
<li>le typage<ul>
<li>typage fort<ul>
<li>statique : déclaration ou bien inférence (déduction) lisible dans le source
(exemple : java)</li>
<li>typage dynamique : une variable est typée en fonction de son contenu</li>
</ul>
</li>
<li>typage faible :<ul>
<li>une donnée naura pas spécialement de type : les nombres, les chaînes de
caractères, les booléens, etc. seront tous des scalaires et ne seront
différenciés que par leur valeur et par le contexte de leur utilisation</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
<a href="search.html"> Recherche</a> | &nbsp;
<!-- a href="genindex.html"> Genindex</a-->
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="Index général"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Index des modules Python"
>modules</a> |</li>
<li class="right" >
<a href="structures.html" title="Structures de contrôle et fonctions"
>suivant</a> |</li>
<li class="right" >
<a href="settings.html" title="Mettre en place son environnement de travail"
>précédent</a> |</li>
<a href="index.html">Programmation python </a> &raquo;
</ul>
</div>
<div class="footer" role="contentinfo">
&#169; Copyright 2015, cadoles (www.cadoles.com).
Créé avec <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>