120 likes | 258 Views
Zen of python. Julien Bouquillon. revolunet revolunet. Productivity Portability Community. #1. Basics. Indentation if y > 42: print "y is bigger than 42" else : print "y is smaller (or equal) than 42" Typage dynamique x = 5 y = 'hello, world' z = Company(name = 'revolunet' )
E N D
Julien Bouquillon revolunet revolunet
#1 Basics Indentation if y > 42: print"y is bigger than 42" else: print"y is smaller (or equal) than 42" Typage dynamique x = 5 y = 'hello, world' z = Company(name = 'revolunet') Assignements x = y = 5 z = 1 < x < 10 # True a, b = 42, 34
#2 Slices une_liste = [1, 2, 3, 'coucou', 4, 5, 6] une_liste[start:end[:step]] une_liste[3] # 'coucou' une_liste[-2] # 5 une_liste[1:3] # 2, 3 une_liste[::3] # [1, 'coucou', 6] une_liste[::-1] # [6, 5, 4, 'coucou', 3, 2, 1] une_liste[::3] = [0, 0, 0] une_liste # [0, 2, 3, 0, 4, 5, 0]
#3 Strings chaine = "bonjour la cantine" chaine[:7] # 'bonjour' chaine.split()[0] # 'bonjour' chaine[::-1] # 'enitnac al ruojnob' print"python rox " * 5 # python rox python rox python rox python rox python rox print"you are %.2f years young" % (3*10) # 'you are 30.00 years old' data = {'firstname':'Guido', 'company':'Google'} print"hello %(firstname)s from %(company)s" % data # 'hello Guido from Google'
#4 Lists comprehension S = [x for x in range(10) if x**2 > 3] # [2, 3, 4, 5, 6, 7, 8, 9] liste1 = [1, 2, 3] liste2 = [3, 4, 5] print [x * y for x in liste1 for y in liste2] # [3, 4, 5, 6, 8, 10, 9, 12, 15]
#5 Decorators modifier le comportement de fonctions existantes def calcul(x, y): return x*y @memoize def calcul(x, y): return x*y @login_required @log(logger = '/var/log/secret_access.log') def view_secret_stuff(request): secret_stuff = ... return secret_stuff
#6 Python requests import requests import simplejson req = requests.get('https://api.github.com/users/revolunet/repos', auth=('revolunet','ucrazy ?')) # convert the Json to a python dictionary data = simplejson.loads(req.content) for repo in data: print repo['name'], ':', repo['description']
#7 POO class Animal(object): ... class Human(Animal): ... class Robot(object): ... class Cyborg(Human, Robot): ... Le comportement de chaque object peut être modifié à volonté - creation, suppression d'objects - comparaisons, opérations... - créer des classes itérables, callables...
#8 Django ORM query filters = { 'author__name__startswith': 'Guido', 'date_published__gte':datetime(2011, 1, 1), 'price__lte':30 } results = Books.objects.filter(**filters) results = results.exclude(publisher__name = 'Eyrolles') results = results.order_by('price')[:50] print results
Merci:) revolunet revolunet