modèle objet de python

This commit is contained in:
gwen
2017-09-05 09:25:48 +02:00
parent 2ddd3e2c18
commit 1645146d0d
17 changed files with 961 additions and 62 deletions

View File

@ -0,0 +1,8 @@
class A:
pass
class B:
pass
a = A()
a.b = B()

View File

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

View File

@ -0,0 +1,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)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,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

View File

@ -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)

View File

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