premiere version stable du cours de poo

This commit is contained in:
gwen
2017-10-02 09:10:51 +02:00
parent 86e9646de9
commit b73e7c85ff
20 changed files with 1016 additions and 406 deletions

View File

@ -0,0 +1,26 @@
Fermetures
-----------
.. glossary::
fermeture
Dans un langage de programmation, une fermeture ou clôture (en anglais : closure) est une fonction accompagnée de son environnement lexical. L'environnement lexical d'une fonction est l'ensemble des variables non locales qu'elle a capturé, soit par valeur (c'est-à-dire par copie des valeurs des variables), soit par référence (c'est-à-dire par copie des adresses mémoires des variables)1. Une fermeture est donc créée, entre autres, lorsqu'une fonction est définie dans le corps d'une autre fonction et utilise des paramètres ou des variables locales de cette dernière. cf : https://fr.wikipedia.org/wiki/Fermeture_(informatique)
.. code-block:: python
>>> def start_at(x):
... def increment_by(y):
... return x + y
... return increment_by
...
>>> closure1 = start_at(1)
>>> closure2 = start_at(2)
>>> closure1(1)
2
>>> closure2(1)
3
With closures, class based programming is syntactic sugar.
https://en.wikipedia.org/wiki/Closure_(computer_programming)

View File

@ -0,0 +1,96 @@
``cli`` : command line interpreter
===================================
As Catherine Devlin, the author of `cmd2 <https://pythonhosted.org/cmd2/>`_ explained it:
| Slightly after the bronze age came the command line interpreter.
| I'm talking about **command line interpreters**
| that is somewhat more specific terms than **command line applications**
| or **command line utilities**
A command line interpreter is a program that is
- plain text
- gives you a prompt
- it gets all of its input at once
- produces his output usually as text lines
- gives you a prompt again
unix shell instructions are a good example of that.
A command line utilities is a unix-like program that gets all of its inputs at once
and gives a result at once.
At the other side, a text user interface is a litlle bit like a gui, it's closer to a gui.
at this time, you have to think of how much effort your interface is worth,
| otherwise it's gonna kill you to write it (Catherine Devlin)
Basic cli functionnalities
---------------------------
A complete command line interpreter written with ``cmd``
- it recognizes the concept of help (contextual help)
- the previous commands (history) can be called again with the keyboard's up and down arrows
- if yout hit Ctr-R and the first letters of a command you can call it again
(bash-style history)
- the tab key will finish out your command
how to use it
--------------
::
>>> 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
.. glossary::
CLI
CLI stands for Command Line Interface, is a tool that, well, it gives you a prompt
.. literalinclude:: ../snippets/cli.py
:caption: basic command line utility library
If you want your :term:`cli` to have more functionalities, try `cm2 <http://www.phyast.pitt.edu/~micheles/python/cmd2.html>`_.
.. important:: Don't use `input()` but `raw_input()` for your command lines

View File

@ -4,6 +4,11 @@ Annexes
.. toctree::
:maxdepth: 2
ojbML
ConstructionParFermeture
cli
symbol
wrapper
surete
agile
scrum

View File

@ -0,0 +1,106 @@
Object en ocaml
===============
::
utop # let myPt =
object
val mutable x = 0
val mutable y = 0
method get_x = x
method get_y = y
method setcoord new_x new_y = x <- new_x ; y<- new_y
end;;
val myPt : < get_x : int; get_y : int; setcoord : int -> int -> unit > = <obj> ─( 17:23:21 )─< command 1 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # myPt#get_x ;;
- : int = 0 ─( 17:23:24 )─< command 2 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # myPt#setcoord 5 89 ;;
- : unit = () ─( 17:23:45 )─< command 3 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # myPt#get_y
;;
- : int = 89
classe point
------------
::
(* ocamlg points.cmo pointClass.ml *)
open Graphics ;;
open Points ;;
open_graph " ";;
set_line_width 5 ;;
set_color magenta ;;
set_window_title "points" ;;
let p1 = new point (0,0)
let p2 = new point (3,4) ;;
p1#lineto (10,28) ;;
p1#lineto (222,55) ;;
print_string (p1#to_string ()) ;;
print_newline () ;;
p1#lineto (50, 125) ;;
ignore (read_key () ) ;;
close_graph () ;;
::
(* l'objet point comme la possibilite de lier
la representation et le dessin sur le graphe
*)
(* ocamlc graphics.cma points.ml *)
class point (x_init,y_init) =
object
val mutable x = x_init
val mutable y = y_init
method get_x = x
method get_y = y
method moveto (a,b) = x <- a ; y <- b
method rmoveto (dx,dy) = x <- x + dx ; y <- y + dy
method lineto (a, b) = Graphics.lineto a b ; x <- a ; y <- b
method to_string () =
"( " ^ (string_of_int x) ^ ", " ^ (string_of_int y) ^")"
method distance () = sqrt (float(x*x + y*y))
end ;;
(*
let p1 = new point (0,0)
let p2 = new point (3,4) ;;
p1#get_x;;
p2#get_y;;
p1#to_string();;
p1#moveto (1,2) ;;
p1#rmoveto (2,5) ;;
p1#to_string () ;;
*)
(* point avec un record
type color = Rouge | Vert | Bleu
type point = {x:int; c:color}
class point (x_init, y_init) =
object
val x = x_init
val y = y_init
method get_x = x
method get_y = y
(* a faire avec le self *)
method moveto (point:p) = point(p.get_a,p.get_b)
method rmoveto (point:p) = point(x + dx, y + dy)
method to_string () =
"( " ^ (string_of_int x) ^ ", " ^ (string_of_int y) ^")"
method distance () = sqrt (float(x*x + y*y))
end ;;
let p1 = new point (0, 0);;
let p2 = new point (3, 4);;
(*
p1#get_x;;
p2#get_y;;
p1#to_string();;
*)

View File

@ -0,0 +1,153 @@
Symbols
=======
Using sets
-----------
There are different ways of defining symbols.
You can do it very simply with sets::
>>> s = set("abc", "def", "ghi")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got 3
>>> s = set(["abc", "def", "ghi"])
>>> s
set(['abc', 'ghi', 'def'])
>>> "abc" in s
True
>>>
If you are using python 3.X, the notation::
Python 3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 in {1,2,3}
True
>>>
is very effective for working with symbols.
Use immutable sets.
Using namespaces
-----------------
Here is a real world example from the tiramisu library
.. code-block:: python
# ____________________________________________________________
class _NameSpace(object):
"""convenient class that emulates a module
and builds constants (that is, unique names)
when attribute is added, we cannot delete it
"""
def __setattr__(self, name, value):
if name in self.__dict__: # pragma: optional cover
raise ConstError(_("can't rebind {0}").format(name))
self.__dict__[name] = value
def __delattr__(self, name): # pragma: optional cover
if name in self.__dict__:
raise ConstError(_("can't unbind {0}").format(name))
raise ValueError(name)
class GroupModule(_NameSpace):
"emulates a module to manage unique group (OptionDescription) names"
class GroupType(str):
"""allowed normal group (OptionDescription) names
*normal* means : groups that are not master
"""
pass
class DefaultGroupType(GroupType):
"""groups that are default (typically 'default')"""
pass
class MasterGroupType(GroupType):
"""allowed normal group (OptionDescription) names
*master* means : groups that have the 'master' attribute set
"""
pass
class OwnerModule(_NameSpace):
"""emulates a module to manage unique owner names.
owners are living in `Config._cfgimpl_value_owners`
"""
class Owner(str):
"""allowed owner names
"""
pass
class DefaultOwner(Owner):
"""groups that are default (typically 'default')"""
pass
class MultiTypeModule(_NameSpace):
"namespace for the master/slaves"
class MultiType(str):
pass
class DefaultMultiType(MultiType):
pass
class MasterMultiType(MultiType):
pass
class SlaveMultiType(MultiType):
pass
# ____________________________________________________________
def populate_groups():
"""populates the available groups in the appropriate namespaces
groups.default
default group set when creating a new optiondescription
groups.master
master group is a special optiondescription, all suboptions should be
multi option and all values should have same length, to find master's
option, the optiondescription's name should be same than de master's
option
groups.family
example of group, no special behavior with this group's type
"""
groups.default = groups.DefaultGroupType('default')
groups.master = groups.MasterGroupType('master')
groups.family = groups.GroupType('family')
def populate_owners():
"""populates the available owners in the appropriate namespaces
default
is the config owner after init time
user
is the generic is the generic owner
"""
setattr(owners, 'default', owners.DefaultOwner('default'))
setattr(owners, 'user', owners.Owner('user'))
def addowner(name):
"""
:param name: the name of the new owner
"""
setattr(owners, name, owners.Owner(name))
setattr(owners, 'addowner', addowner)
# ____________________________________________________________
# populate groups and owners with default attributes
groups = GroupModule()
populate_groups()
owners = OwnerModule()
populate_owners()

View File

@ -0,0 +1,53 @@
Wrapping
=========
a wrapper can restrict, heritage cannot.
::
# ____________________________________________________________
# Base objects
class Element:
def __init__(self, name):
self.name = name
def __repr__(self):
return "<Element %s>"% self.name
# ____________________________________________________________
# Wrapped objects
class W_Element:
def __init__(self, name, wrap):
self._name = "wrapped_element" or name
self._w = wrap
def __getattr__(self, name):
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)
# ____________________________________________________________
# tests
e = Element('element 1')
w_e = W_Element('w_element 1', e)
e.a = 2
print w_e.a
print w_e
w_e.b = 5
print w_e.b