Python pour les dévs PHP

Arthur Vuillard, #!⌨

Python pour les dévs PHP

Arthur Vuillard, #!⌨

Python

Usages

Philosophie

Exemple

def factorial(number):
    if number in [0, 1]:
        return 1
    else:
        return number * factorial(number - 1)
 
factorial(10)
# 3628800

Programmation objet

class MyClass:
    """A simple example class"""
    number = 12345
 
    def __init__(self, name):
        self.name = name
 
    def method(self):
        return 'hello %s %d' % (self.name, self.number)

Programmation objet

object = MyClass('AFUP')
print object.name
# AFUP
print object.number
# 12345
print object.method()
# hello AFUP 12345

Programmation objet

print object
# <__main__.MyClass instance at 0xb731a0ec>
print object.method
# <bound method MyClass.method of <__main__.MyClass instance at 0xb734c0ec>>

Programmation objet

Typage fort

print type(1)
# <type 'int'>
print type(1.0)
# <type 'float'>
print type('a')
# <type 'str'>
print type(u'a')
# <type 'unicode'>

Typage fort

class Test(object):
    pass
 
o = Test()
print type(o)
# <class '__main__.Test'>

Typage fort

type([0, 1, 'a'])
# <type 'list'>
type({'key': 'value'})
# <type 'dict'>
type({'element'})
# <type 'set'>
type(('e1', 'e2',))
# <type 'tuple'>

Duck typing

class Duck(object):
    def quack(self):
        print 'COIN'
class DuckRobot(object):
    def quack(self):
        print 'BIP'
 
def make_it_quack(o):
    o.quack()

Duck typing

duck = Duck()
make_it_quack(duck)
# COIN
 
robot = DuckRobot()
make_it_quack(robot)
# BIP

Trucs grave cool : les générateurs

Trucs grave cool : les générateurs

for square in squares():
    print square
    if square == 25:
        break

Trucs grave cool : les compréhension de liste

squares = [x ** 2 for x in range(10)]
print squares
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Piles inclues

Frameworks webs

from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "Hello World!"
 
if __name__ == "__main__":
    app.run()

Pas cool

Pour aller plus loin

Des questions ?

Arthur Vuillard, #!⌨, arthur@hashbang.fr