import de la formation python de Gwen
This commit is contained in:
parent
38d5676bfa
commit
364778079e
|
@ -0,0 +1,153 @@
|
|||
# Makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line.
|
||||
SPHINXOPTS =
|
||||
SPHINXBUILD = sphinx-build
|
||||
PAPER =
|
||||
BUILDDIR = _build
|
||||
|
||||
# Internal variables.
|
||||
PAPEROPT_a4 = -D latex_paper_size=a4
|
||||
PAPEROPT_letter = -D latex_paper_size=letter
|
||||
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||
# the i18n builder cannot share the environment and doctrees with the others
|
||||
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
||||
|
||||
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
||||
|
||||
help:
|
||||
@echo "Please use \`make <target>' where <target> is one of"
|
||||
@echo " html to make standalone HTML files"
|
||||
@echo " dirhtml to make HTML files named index.html in directories"
|
||||
@echo " singlehtml to make a single large HTML file"
|
||||
@echo " pickle to make pickle files"
|
||||
@echo " json to make JSON files"
|
||||
@echo " htmlhelp to make HTML files and a HTML help project"
|
||||
@echo " qthelp to make HTML files and a qthelp project"
|
||||
@echo " devhelp to make HTML files and a Devhelp project"
|
||||
@echo " epub to make an epub"
|
||||
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
|
||||
@echo " latexpdf to make LaTeX files and run them through pdflatex"
|
||||
@echo " text to make text files"
|
||||
@echo " man to make manual pages"
|
||||
@echo " texinfo to make Texinfo files"
|
||||
@echo " info to make Texinfo files and run them through makeinfo"
|
||||
@echo " gettext to make PO message catalogs"
|
||||
@echo " changes to make an overview of all changed/added/deprecated items"
|
||||
@echo " linkcheck to check all external links for integrity"
|
||||
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
|
||||
|
||||
clean:
|
||||
-rm -rf $(BUILDDIR)/*
|
||||
|
||||
html:
|
||||
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||
|
||||
dirhtml:
|
||||
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
|
||||
|
||||
singlehtml:
|
||||
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
|
||||
|
||||
pickle:
|
||||
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
|
||||
@echo
|
||||
@echo "Build finished; now you can process the pickle files."
|
||||
|
||||
json:
|
||||
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
|
||||
@echo
|
||||
@echo "Build finished; now you can process the JSON files."
|
||||
|
||||
htmlhelp:
|
||||
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run HTML Help Workshop with the" \
|
||||
".hhp project file in $(BUILDDIR)/htmlhelp."
|
||||
|
||||
qthelp:
|
||||
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
|
||||
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
|
||||
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python.qhcp"
|
||||
@echo "To view the help file:"
|
||||
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python.qhc"
|
||||
|
||||
devhelp:
|
||||
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
|
||||
@echo
|
||||
@echo "Build finished."
|
||||
@echo "To view the help file:"
|
||||
@echo "# mkdir -p $$HOME/.local/share/devhelp/python"
|
||||
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python"
|
||||
@echo "# devhelp"
|
||||
|
||||
epub:
|
||||
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
|
||||
@echo
|
||||
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
|
||||
|
||||
latex:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo
|
||||
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
|
||||
@echo "Run \`make' in that directory to run these through (pdf)latex" \
|
||||
"(use \`make latexpdf' here to do that automatically)."
|
||||
|
||||
latexpdf:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through pdflatex..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
text:
|
||||
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
|
||||
@echo
|
||||
@echo "Build finished. The text files are in $(BUILDDIR)/text."
|
||||
|
||||
man:
|
||||
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
|
||||
@echo
|
||||
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
|
||||
|
||||
texinfo:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo
|
||||
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
|
||||
@echo "Run \`make' in that directory to run these through makeinfo" \
|
||||
"(use \`make info' here to do that automatically)."
|
||||
|
||||
info:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo "Running Texinfo files through makeinfo..."
|
||||
make -C $(BUILDDIR)/texinfo info
|
||||
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
|
||||
|
||||
gettext:
|
||||
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
|
||||
@echo
|
||||
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
|
||||
|
||||
changes:
|
||||
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
|
||||
@echo
|
||||
@echo "The overview file is in $(BUILDDIR)/changes."
|
||||
|
||||
linkcheck:
|
||||
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
|
||||
@echo
|
||||
@echo "Link check complete; look for any errors in the above output " \
|
||||
"or in $(BUILDDIR)/linkcheck/output.txt."
|
||||
|
||||
doctest:
|
||||
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
|
||||
@echo "Testing of doctests in the sources finished, look at the " \
|
||||
"results in $(BUILDDIR)/doctest/output.txt."
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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; }
|
Binary file not shown.
After Width: | Height: | Size: 24 KiB |
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
|
@ -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;
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
{% extends "!layout.html" %}
|
||||
|
||||
{% block rootrellink %}
|
||||
<a href="{{ pathto('index') }}">Programmation python </a> »
|
||||
{% endblock %}
|
||||
|
||||
{% block relbar1 %}
|
||||
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
|
||||
<table><tr><td>
|
||||
<img src="{{ pathto('_static/sphinx.png', 1) }}" alt="logo" />
|
||||
</td><td>
|
||||
<h1> Programmation python</h1>
|
||||
</td></tr></table>
|
||||
</div>
|
||||
{{ super() }}
|
||||
{% endblock %}
|
||||
|
||||
{% block sidebar1 %}
|
||||
<p> </p>
|
||||
{% endblock %}
|
||||
|
||||
{% block sidebar2 %}
|
||||
<div style="background-color: white; text-align: left; padding: 10px 10px 15px 15px">
|
||||
<a href="{{ pathto('search') }}"> {{ _('Search') }}</a> |
|
||||
<!-- a href="{{ pathto('genindex') }}"> {{ _('Genindex') }}</a-->
|
||||
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
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**
|
||||
|
||||
classes d'objets
|
||||
------------------
|
||||
|
||||
- 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'
|
||||
>>>
|
|
@ -0,0 +1,244 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# python documentation build configuration file, created by
|
||||
# sphinx-quickstart on Mon Oct 29 15:39:07 2012.
|
||||
#
|
||||
# This file is execfile()d with the current directory set to its containing dir.
|
||||
#
|
||||
# Note that not all possible configuration values are present in this
|
||||
# autogenerated file.
|
||||
#
|
||||
# All configuration values have a default; values that are commented out
|
||||
# serve to show the default.
|
||||
|
||||
import sys, os
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#sys.path.insert(0, os.path.abspath('.'))
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinx.ext.todo', 'sphinx.ext.pngmath']
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.txt'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'python'
|
||||
copyright = u'2012, cadoles (www.cadoles.com)'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '1'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '0'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
language = 'fr'
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = ['_build']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'default'
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
#html_theme_path = []
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
#html_title = None
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['_static']
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
#html_sidebars = {}
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = None
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
htmlhelp_basename = 'pythondoc'
|
||||
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
latex_elements = {
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#'papersize': 'letterpaper',
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#'pointsize': '10pt',
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#'preamble': '',
|
||||
}
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
latex_documents = [
|
||||
('index', 'python.tex', u'python Documentation',
|
||||
u'gwen', 'manual'),
|
||||
]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
|
||||
# -- Options for manual page output --------------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'python', u'python Documentation',
|
||||
[u'gwen'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#man_show_urls = False
|
||||
|
||||
|
||||
# -- Options for Texinfo output ------------------------------------------------
|
||||
|
||||
# Grouping the document tree into Texinfo files. List of tuples
|
||||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
('index', 'python', u'python Documentation',
|
||||
u'gwen', 'python', 'One line description of project.',
|
||||
'Miscellaneous'),
|
||||
]
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#texinfo_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#texinfo_domain_indices = True
|
||||
|
||||
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
||||
#texinfo_show_urls = 'footnote'
|
||||
|
||||
todo_include_todos = True
|
|
@ -0,0 +1,5 @@
|
|||
Liste des exercices
|
||||
--------------------
|
||||
|
||||
.. todolist::
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
.. 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.
|
||||
|
||||
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")
|
||||
|
||||
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)
|
||||
|
||||
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 SimpleHTTPServer 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
|
Binary file not shown.
After Width: | Height: | Size: 134 KiB |
Binary file not shown.
After Width: | Height: | Size: 146 KiB |
|
@ -0,0 +1,30 @@
|
|||
|
||||
apprentissage de la programmation avec python
|
||||
----------------------------------------------
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
getting-started
|
||||
settings
|
||||
type
|
||||
structures
|
||||
prompt
|
||||
|
||||
programmation python, connaissances de base
|
||||
--------------------------------------------
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
classes
|
||||
specialmethods
|
||||
stdlib
|
||||
testsunitaires
|
||||
|
||||
Index et recherche
|
||||
-------------------
|
||||
|
||||
* :doc:`exercices`
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
|
@ -0,0 +1,108 @@
|
|||
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>
|
||||
|
||||
to add a command, just use inheritance::
|
||||
|
||||
|
||||
>>> 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'
|
||||
>>>
|
|
@ -0,0 +1,96 @@
|
|||
Mettre en place son environnement de travail
|
||||
=============================================
|
||||
|
||||
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
|
||||
|
||||
.. 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
|
||||
|
||||
configurer son éditeur
|
||||
----------------------
|
||||
|
||||
- les fichiers sources ont l'extenstion `.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':'/home/gwen/local
|
||||
|
||||
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()
|
|
@ -0,0 +1,8 @@
|
|||
class A:
|
||||
pass
|
||||
|
||||
class B:
|
||||
pass
|
||||
|
||||
a = A()
|
||||
a.b = B()
|
|
@ -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")
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
Module docstring.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import optparse
|
||||
|
||||
def process_command_line(argv):
|
||||
"""
|
||||
Return a 2-tuple: (settings object, args list).
|
||||
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
|
||||
"""
|
||||
if argv is None:
|
||||
argv = sys.argv[1:]
|
||||
|
||||
# initialize the parser object:
|
||||
parser = optparse.OptionParser(
|
||||
formatter=optparse.TitledHelpFormatter(width=78),
|
||||
add_help_option=None)
|
||||
|
||||
# define options here:
|
||||
parser.add_option( # customized description; put --help last
|
||||
'-h', '--help', action='help',
|
||||
help='Show this help message and exit.')
|
||||
|
||||
settings, args = parser.parse_args(argv)
|
||||
|
||||
# check number of arguments, verify values, etc.:
|
||||
if args:
|
||||
parser.error('program takes no command-line arguments; '
|
||||
'"%s" ignored.' % (args,))
|
||||
|
||||
# further process settings & args if necessary
|
||||
|
||||
return settings, args
|
||||
|
||||
def main(argv=None):
|
||||
settings, args = process_command_line(argv)
|
||||
# application code here, like:
|
||||
# run(settings, args)
|
||||
return 0 # success
|
||||
|
||||
if __name__ == '__main__':
|
||||
status = main()
|
||||
sys.exit(status)
|
|
@ -0,0 +1,10 @@
|
|||
def helloworld(ob):
|
||||
print "Hello world"
|
||||
return ob
|
||||
|
||||
@helloworld
|
||||
def myfunc():
|
||||
print "my function"
|
||||
|
||||
myfunc()
|
||||
print myfunc
|
|
@ -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())
|
|
@ -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
|
|
@ -0,0 +1,15 @@
|
|||
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?")
|
||||
|
||||
|
|
@ -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()
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
class Sorter:
|
||||
def sort(self, list):
|
||||
for i in range(len(list) - 1):
|
||||
for j in range(i, len(list)):
|
||||
if self.compareItems(list[i], list[j]):
|
||||
list[i], list[j] = list[j], list[i]
|
||||
|
||||
def getName(self):
|
||||
return "Trieur de liste"
|
||||
|
||||
def getDescription(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def compareItems(self, item1, item2):
|
||||
raise NotImplementedError
|
||||
|
||||
class AscendantSorter(Sorter):
|
||||
def compareItems(self, item1, item2):
|
||||
return item1 >= item2
|
||||
def getDescription(self):
|
||||
return "Tri par ordre normal"
|
||||
def getName(self):
|
||||
return "Ascendant"
|
||||
|
||||
class DescendantSorter(Sorter):
|
||||
def compareItems(self, item1, item2):
|
||||
return item1 <= item2
|
||||
def getDescription(self):
|
||||
return "Tri par ordre inverse"
|
||||
|
||||
if __name__ == '__main__':
|
||||
list = ['b', 'e', 'a', 'c', 'z']
|
||||
s = AscendantSorter()
|
||||
s.sort(list)
|
||||
print list
|
||||
s = DescendantSorter()
|
||||
s.sort(list)
|
||||
print list
|
|
@ -0,0 +1,10 @@
|
|||
class Zone(object):
|
||||
def __init__(self, name, level=0):
|
||||
self.name = name
|
||||
self.level = level
|
||||
|
||||
def __add__(self, other):
|
||||
return Zone(self.name + other.name, level=self.level+other.level)
|
||||
|
||||
def __cmp__(self, other):
|
||||
return cmp(self.level, other.level)
|
|
@ -0,0 +1,22 @@
|
|||
class Wrap(object):
|
||||
def __init__(self, name, wrap):
|
||||
self.slots = ('_name', '_wrap')
|
||||
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)
|
|
@ -0,0 +1,229 @@
|
|||
Programmation python courante
|
||||
================================
|
||||
|
||||
.. _namespaces:
|
||||
|
||||
les espaces de nommage
|
||||
-----------------------
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
.. todo:: émulation de defaultdict
|
||||
|
||||
Dict with a default value
|
||||
--------------------------
|
||||
|
||||
il est possible d'hériter des types de base
|
||||
|
||||
>>> a = dict.defaultdict(default=0)
|
||||
>>> a
|
||||
{}
|
||||
>>> a[1] = 2
|
||||
>>> print a
|
||||
{1: 2}
|
||||
>>> a[0]
|
||||
0
|
||||
>>> a.keys()
|
||||
[1]
|
||||
>>> a["machin"]
|
||||
0
|
||||
|
||||
::
|
||||
|
||||
class defaultdict(dict):
|
||||
|
||||
def __init__(self, default=None):
|
||||
dict.__init__(self)
|
||||
self.default = default
|
||||
|
||||
def __getitem__(self, key):
|
||||
try:
|
||||
return dict.__getitem__(self, key)
|
||||
except KeyError:
|
||||
return self.default
|
||||
|
||||
def __getitem__(self, key):
|
||||
if key in self:
|
||||
return dict.__getitem__(self, key)
|
||||
else:
|
||||
return self.default
|
||||
|
||||
def get(self, key, *args):
|
||||
if not args:
|
||||
args = (self.default,)
|
||||
return dict.get(self, key, *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'
|
||||
|
||||
>>> 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
|
|
@ -0,0 +1,208 @@
|
|||
La :term:`librairie standard`
|
||||
================================
|
||||
|
||||
.. 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
|
|
@ -0,0 +1,305 @@
|
|||
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 ?
|
||||
|
||||
la programmation par exceptions
|
||||
-------------------------------------
|
||||
|
||||
>>> 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
|
||||
>>
|
||||
|
||||
.. important:: règle du Samouraï : une fonction doit renvoyer le résultat escompté
|
||||
ou bien lever une exception
|
||||
|
||||
|
||||
programmation objet
|
||||
--------------------
|
||||
|
||||
- la programmation objet définit des classes
|
||||
- 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
|
||||
|
||||
>>> class A:
|
||||
... pass
|
||||
...
|
||||
>>> a = A()
|
||||
>>> a.a = 2
|
||||
>>> def function(x):
|
||||
... print x
|
||||
...
|
||||
>>> a.f = function
|
||||
>>> a.f("hello")
|
||||
hello
|
||||
>>>
|
||||
|
||||
- instance de classe : on peut créer des objets à partir d'un type "classe"
|
||||
(une classe est instanciable)
|
||||
|
||||
- définition d'une classe :
|
||||
|
||||
méthode classique :
|
||||
|
||||
>>> class A:
|
||||
... pass
|
||||
...
|
||||
|
||||
méthode dynamique (la fonction :func:`type` est ici un **constructeur** :
|
||||
|
||||
>>> type("A", (), {})
|
||||
<class '__main__.A'>
|
||||
>>> A = type("A", (), {})
|
||||
>>> a = A()
|
||||
>>> type(a)
|
||||
<class '__main__.A'>
|
||||
|
||||
types et classe
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
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
|
||||
|
||||
.. todo:: tout hérite de la classe `object`
|
||||
|
||||
>>> object
|
||||
<type 'object'>
|
||||
>>> type(object)
|
||||
<type 'type'>
|
||||
>>> type(type)
|
||||
<type 'type'>
|
||||
>>> type(type(type))
|
||||
<type 'type'>
|
||||
>>> isinstance(type, object)
|
||||
True
|
||||
>>> isinstance(object, object)
|
||||
True
|
||||
|
||||
**conclusion** : en python un type et une classe c'est la même chose. Une classe
|
||||
est un type standard !
|
|
@ -0,0 +1,153 @@
|
|||
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`
|
||||
|
||||
.. 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 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()
|
||||
|
||||
|
||||
traiter une exception avec
|
||||
|
||||
::
|
||||
|
||||
try:
|
||||
...
|
||||
except:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
else:
|
||||
bla bla
|
||||
finally:
|
||||
bla bla
|
||||
|
||||
|
||||
créer le plus possible ses propres exceptions spécifiques au programme
|
||||
|
||||
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
|
|
@ -0,0 +1,625 @@
|
|||
.. 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é
|
||||
- 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 opté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= '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']
|
||||
>>>
|
||||
|
||||
- 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
|
||||
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
|
||||
|
||||
- l'encodage (unicode):
|
||||
|
||||
>>> u = u"éèà bla"
|
||||
>>> u
|
||||
u'\xe9\xe8\xe0 bla'
|
||||
>>> u.encode("utf-8")
|
||||
'\xc3\xa9\xc3\xa8\xc3\xa0 bla'
|
||||
>>> print u.encode("utf-8")
|
||||
éèà bla
|
||||
>>>
|
||||
|
||||
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.decode("utf-8")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
|
||||
return codecs.utf_8_decode(input, errors, True)
|
||||
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
|
||||
|
||||
- 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']
|
||||
>>>
|
||||
.. 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 :
|
||||
|
||||
::
|
||||
|
||||
>>> import sets
|
||||
>>> e = sets.Set()
|
||||
>>> e
|
||||
Set([])
|
||||
|
||||
>>> import sets
|
||||
>>> e = sets.Set("toto")
|
||||
>>> e
|
||||
Set(['t', 'o'])
|
||||
>>> d = {"a":1,"b":2}
|
||||
>>> f = sets.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
|
||||
</pre>
|
||||
Ajout :
|
||||
<pre class="shell">
|
||||
>>> e.add("a")
|
||||
>>> e
|
||||
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
|
||||
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 :
|
||||
<pre class="shell">
|
||||
>>> 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 < e
|
||||
True
|
||||
>>> f > 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 :
|
||||
<pre class="shell">
|
||||
>>> 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])
|
||||
|
||||
Manipulations diverses
|
||||
|
||||
::
|
||||
|
||||
>>> ''.join( sets.Set('ciao there!') & sets.Set('hello!') )
|
||||
'!heo'
|
||||
|
||||
Set(['a', 0, 2, 3, 4, 1])
|
||||
>>> f = e.copy()
|
||||
>>> f
|
||||
Set(['a', 0, 2, 3, 4, 1])
|
||||
>>> f.remove(0)
|
||||
>>> 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
|
Loading…
Reference in New Issue