You are on page 1of 32

IntroduccinaPython

LibreraEstndar Frameworks

JosFlixOntanCarmona
felixonta@gmail.com

ndice
1.Python:

2.LibreraEstndar

Introduccin ModoInteractivo TiposyEstructurasdeDatos SentenciasdeControldeFlujo EntradaySalida DefinicindeFunciones Excepciones MdulosyPaquetes OrientacinaObjeto

MdulosEstndar Ejemplos

3.Frameworks

Twisted Turbogears pyGame wxPython

4.Bibliografa

Python

Introduccin
Historia SudesarrollocominezaconGuidoVanRossumen1990 Elnombre'Python'provienedelgrupocmicoMonthyPython Caractersticas LenguajeInterpretado/'Compilado'deMuyAltoNivel Depropsitogeneral ProgramacinenparadigmasProcedimentalyOrientadoaObjeto Dbilmentetipado Multiplataforma(Crossplatform) Estructuradelcdigo Findelneamarcafindesentencia Elsangradoexpresalaestructuradebloque
foo = 'bar' if foo == 'bar': print 'ok' else: if foo == 'rab': print 'it's rab'

ModoInteractivo
Elmodointeractivopythonmuestralashellpython,atravsdelacual podemosejecutarordenespythoncomosideunaconsolasetratase.
Accedemosalconsoloejecutarelcomando'python' Mejormaneradeaprenderyfamiliarizarseconellenguaje Contieneunmododeayuda Pruebaydepuratusideasaqu

Alternativas:Idle,PyCrust,Spe...

TiposyEstructurasdeDatos(I)
Numericos: a=132 b=34*75 c=45/34 a+b (integer) i=2L j=1000L**3 k=4L/2L i+a (long) f=756.123 g=55.3*23 h=45.0/34.0 f+j (float) x=1+0j y=12.070j*13 z=1+1j/11j x+f (complex)
Notas: Ladivisincon enterostrunca decimales Pythonsoporta enteroslargoscon longitudilimitada

Cadenas: Nota: |H|e|l|p| 01234 4321


>>> cad='foobar' >>> cad[0] 'f' >>> len(cad) 6 >>> cad[:3] 'foo' >>> cad[3:] 'bar' >>> cad[1:5] 'ooba' >>> cad[-4] 'b' >>> cad[:-1] 'fooba' >>> cad[-4:] 'obar' >>> cad+' raboof' 'foobar raboof' >>> cad.capitalize() 'Foobar' >>> cad.upper() 'FOOBAR'

TiposyEstructurasdeDatos(II)
DisponemosenPythondevariosTipos(estructuras)deDatosCompuestosdeforma nativa.Losmscomunes,tilesyverstilessonlasListasylosDiccionarios.Pueden agruparelementosdedistintosTipospararealizaroperacionessobreellos. Listas:Conjuntodeelementosindexados separadosporcomas Diccionarios:Conjuntodeparesclavevalor

>> dic = {'nombre':'Juan','edad':23,'sexo':'M'} >> dic['nombre'] >> list = ['casa'] >> list.count(123) 'Juan' >> list.append[123] 2 >> dic.keys() >> list.insert[0,'boca'] >> list.pop() ['nombre','edad','sexo'] ['boca','casa',123] 123 >> dic.values() >> list.sort() >> nest = [12,'a'] ['Juan',23,'M'] >> list >> list.append(nest) >> dic[144] = 'Euros' [123,'boca','casa'] >> list >> list[0:2] [123,'boca','casa',[12,'a']] >> dic {'nombre':'Juan','edad':23,'sexo':'M',144:'Euros'} [123,'boca'] >> len(list) >> dic >> list[-1] 4 >> len(dic) 'casa' 4 >> list.append(123)

SentenciasdeControldeFlujo
if<condicion>: <sentencias> elif<condicion>: <sentencias> else: <sentencias>
>> lista1 = [1,2,3] >> lista2 = [3,4,5] >> if lista1 == [1,2,3]: ... print 'si' si >> if lista1 > lista2: ... print 'Mayor' ... elif lista1 < lista2: ... print 'Menor' ... else: print 'Igual' Mayor

for<variable>in<secuencia>: <sentencias>
>> for numero in range(1,3): .... print numero 1 2 3 >> coord = [(1,1),(1,2),(3,4)] >> for x,y in coord: ... print x,y 11 12 34 >> alpha = {1:'a',3:'c',2:'b'} >> numeros = alpha.keys() >> numeros.sort() >> for numero in numeros: ... print alpha[numero] a b c

while<condicion>: <sentencias>
>> x = 5 >> while x < 0: ... print x, ... x = x -1 54321 >> x = 5 >> while True: ... x = x -1 ... if x == 3: ... continue ... if x == 0: break ... print x, 421

EntradaySalida
Comoentodolenguaje,podemostrabajarconlaE/Sdelaaplicacinatravsdetecladoy pantallaoatravsdeficheros.Pythonaadealgunascomodidadesalrespecto. Clasica Podemossolicitarvaloresportecladocon raw_inputypresentarvaloresporpantallacon print.Pythonescapazderepresentar cualquierestructuradedatosenformato legible'parahumanos'
>> nombre = raw_input('Nombre: ') Nombre: Jose >> edad = 24 >> print '%s tiene %d' % (nombre,edad) Jose tiene 24 >> file = open('foo.txt','w') >> file.write(datos[0]) >> file.close()

Mejoras/Comodidades ModulocPickle:Guardaryrecupera desdearchivoscualquiertipodedato,e inclusoinstanciasdeclases.


>> import cPickle >> datos = {'Nombre':'Jose','Edad':24} >> file = open('foo.txt','w') >> cPickle.dump(f, datos) >> file.close() >> file = open('foo.txt','r') >> copia = cPickle.load(file) >> copia['Nombre'] Jose

DefinicindeFunciones(I)
Secreanconlapalabrareservada'def'
>> def holamundo(): ... print 'hola mundo' >> holamundo() hola mundo >> def sumados(numero): ... return numero + 2 >> print sumados(3) 5 >> x=5 >> def dameUnaX(x): .. print x >> dameUnaX(4) 4 >> def punto(x=0,y=0): ... print '('+x+','+y+')' >> punto() (0,0) >> punto(y=3) (0,3)

No se distingue explcitamente entre funciones (devuelven valor) y procedimientos (no devuelvenvalor)

Cadafuncindefinesupropioespaciodenombres (namespace)

Todoslosargumentossepasanporreferencia.Los argumentospuedenpasarsedeformaposicionalo nombradayconvalorespordefecto

DefinicindeFunciones(II)
Unafuncinpuededevolvercualquiertipo oestructuradedatosPython
>> def dameHora(): ... return (15,10) >> hora,minuto = dameHora() >> print '%d:%d' % (hora,minuto) 15:10 >> def calculadora(operacion, op1,op2): .. return operacion(op1,op2) >> def suma(sum1,sum2): ... return sum1+sum2 >> def resta (res1,res2): ... return res1-res2 >> print calculadora(suma, 5, 3) 8 >> print calculadora(resta, 5, 3) 2 >> def carrito(dueo, *articulos): ... print dueo+' Ha comprado:', ... for articulo in articulos: ... print articulo, >> carrito('Pedro','Champ','Leche') Pedro Ha comprado: Champ Leche

Unafuncinpuederecibircomoparmetro otrafuncin.Aspodemoscrearfunciones queencapsulenelcomportamientodeotras ocrearfuncionesgenricasmodificables porelcomportamientodelafuncinquele suministremoscomoparmetro. Con*argenlacabeceradelafuncinse recibentodoslosargumentoscomouna lista.Podemos,as,construirfuncionescon nmerovariabledeargumentos

Excepciones
Seusanlasexcepcionesparaelmanejodeerroresynotificacindeeventosenelflujode unaaplicacin.Pythonlanza,pordefecto,mltiplesinterrupcionesantecomportamientos inesperados,cerrandolaaplicacinydevolviendounatrazadelprograma.Eslabordel programadorcapturarytratardichasinterrupciones.Seutilizanbloquestry...except
>> try: ... print 2/0 ... except: ... print 'Salto una Excepcin' Salto una Excepcin >> try: ... print 2/0 ... except ZeroDivisionError: print 'No se divide por 0' ... except: ... print 'Salto una Excepcin' No se divide por 0 >> letras=['a','b,'c'] >> def dameLetra(pos): ... try: ... letra = letras[pos] ... file = open('letra.txt') ... file.write(letra) ... file.close() ... except (IOError, IndexError): ... print 'No se pudo' >> dameLetras(4) No se pudo

MdulosyPaquetes
Mdulo:Coleccindeclases,funcionesyvariablessalvadasenunarchivo.py Seimportanconlapalabrareservada >> import math >> math.cos(0) importseguidadelnombredelmdulo(sin 1.0 incluirlaextensin)

Podemosimportarunmodulocompletoo >> print upper('big'), lower('LITTLE') clasesyfuncionesindependientesconfrom BIG little

>> from string import upper, lower

Paquete:Coleccindemdulossituadosenunmismodirectorio.Paraqueun directorioseareconocidocomopaqueteesnecesarioquestecontengaunarchivo llamado__init__.pyquepuedeestarvaco.Unpaquetepuedecontenersubpaquetes (subdirectorios,cadaunoconsu__init__.py) Anlogamentepodemosimportarpaquetes enterosomdulosysubpaquetes independientes

>> import mates.algebra >> mates.algebra.seno(0) 0.0

Nota:Puedeobservarseelcontenidodeunmduloopaqueteconlafuncindir()

OrientacinaObjeto(I)
Pythonimplementalaorientacinaobjetosoportandoclaseseinstancias. EnPython,unaclaseestratadacomounaplantillaatravsdelacualcrearinstancias. Unobjetocreadoapartirdeunaclaseesunainstanciadelaclase Elprimerargumentoentodomtododeunaclaseesunareferenciaalobjeto.Por convencinseusaself

import math class vector: p1=(0,0) p2=(0,0) def dameDireccion(self): return ( self.p2[0] - self.p1[0], self.p2[1] - self.p1[1]) def dameModulo(self): return math.sqrt((self.p1[0]+self.p2[0])**2 + (self.p1[1]+self.p2[1])**2)

>> vec = vector() >> vec.p1 = (1,2) >> vec.p2 = (2,1) >> print vec.dameDireccion() (1, -1) >> print vec.dameModulo() 4.2426406871192848

OrientacinaObjeto(II)
Cadainstanciaheredaelcomportamientoyatributosdefinidoenlaclaseydefinesu propio espacio de nombres. Los atributos de una clase pueden ser creados dinmicamente.Todoslosatributosymtodosdeunaclasesonpblicos.
class pub: a='publico' b='tambien' def nuevo(self, s): self.c = s def dame(self): print self.a, self.b >> foo=pub() >> foo.nuevo('new') >> foo.c 'new' >> foo.dame() publico tambien >> bar=priv() >> bar._a 'no debes' >> bar.__b Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: a instance has no attribute '__b' >> bar.dame() no debes no puedes

Porconvencin: Atributo/Mtodoque comienzacon_(guin bajo)nodebeser usadoexternamente


Atributo/Mtodoque class priv: _a = 'no debes' comienzacon__(doble __b = 'no puedes' guinbajo)noes exportado def dame(self): directamente.

print self._a, self.__b

OrientacinaObjeto(III)
Pythondispone,enelparadigmaorientadoaobjeto,delosllamadosmtodosespeciales medianteloscualespodemossobreescribirelcomportamientodelosmtodosinternos (builinmethods).Todomtodoespecialsiguelanomenclatura__nombremetodo__()
class punto3D: def __init__(self,x=0,y=0,z=0): self.x = x self.y = y self.z = z def __add__(self, other): x = self.x + other.x y = self.y + other.y z = self.z + other.z return punto3D(x,y,z) def __str__(self): return '(%d,%d%d)' % (self.x,self.y,self.z) >> a = punto3D(1,1,1) >> print a (1,1,1) >> a = punto3D(y=2) >> b = punto3D(1,0,1) >> print a, b (1,0,1) (0,2,0) >> c = a + b >> print c (1,2,1)

Algunosmtodosespeciales __len__:definireltamao quesedevuelveallamar len(objeto) __sub__:restardosobjetos __cmp__:comparardos objetoscon<,>, ==,etc... __getitem__:soportar indexado,ej:objeto[0]

OrientacinaObjeto(IV)
Unasubclaseheredalosmtodosyatributosdeotraquellamamosclasebase.Aestose lellamaherencia.Elpolimorfismo(mtodosquesoncapacesdeoperarcondistintostipos ynmerosdeargumentos)noestimplementadoenPythonperosepuedeprogramar.
class punto2D(punto3D): def __init__(self, x=0, y=0): vector3D._init_(x,y,0) def __add__(self, other): x = self.x + other.x y = self.y + other.y return punto2D(x,y) def __sub__(self, other): return self.__add__(not other) def __not__(self): return punto2D(-self.x, -self.y) def __str__(self): return '(%d,%d)' % (self.x,self.y) class recta: def __init__(self, p1, p2): if type(p1)==type(p2)=='tuple': self.p1 = punto2D(p1[0],p1[1]) self.p2 = punto2D(p2[0],p2[1]) else: self.p1 = p1 self.p2 = p2 def direccion(self): return self.p2-self.p1 >> m = recta(punto2D(1,1),punto2D(3,1)) >> m.direccion() '(2, 0)' >> m = recta((2,2),(3,1)) >> print m.p1+m.p2 (5,3)

LibreraEstndar
Unaaproximacinprctica

Introduccin
SegnseleeenO'ReillyPythonStandarLibrary: LalibreraestndardePythoncubreunampliorangodemdulos. IncluyetodoslosmdulosquesonpartedelpropiolenguajePython, comolostiposdedatosysentenciasdefinidasenlaespecificacin dellenguaje,amdulosquesonprobablementetilessoloaun nmeroreducidodeprogramas Aspues,enlalibreraestndardepythonencontramosmdulosypaquetes pararealizar:

Manejodecadenas,fechas,etc... AdministracinyServiciosdelSistemaOperativo Expresionesregulares Protocolosdered ProgramacinDistribuida ...

Datetime
Elmdulodatetimeenglobalasclases,funcionesyvariablesnecesariasparaelmanejo defechasyhoras.Estaimplementacinsoportaoperacionesdefechas(sumar,restar,etc...) ydiversastransformaciones(acalendario,timestamp,fechaiso...)
import datetime people = {'Manuel': '20-03-1999', 'Pedro': '18-12-1981'} anyos = 0 for cadenaFecha in people.values(): campos = cadenaFecha.split('-') fecha = datetime.date(int(campos[2]), int(campos[1]), int(campos[0])) diferencia = datetime.date.today() - fecha anyos = anyos + (diferencia.days / 360) nombres = str(people.keys())[2:-2].replace("'","") print 'Las edades de: %s suman %d' % (nombres, anyos)

AdministracinyServiciosdelSO(I)
Paqueteos
Proveedeunainterfazunificadadeaccesoalosserviciosdediversossistemas operativos(Posix,nt,mac,dos...).Programasquehaganunusocorrectodelpaquete ostienenmsoportunidadesdesermultiplataforma.

Adestacar: Mduloos.path:Funcionesparalagestinderutasyarchivos Mduloos.walk:Capazdecaminaratravsdeunrboldedirectorios LlamadasalSistemaOperativo:os.kill,os.execv,os.fork,os.pipe

Mdulosys
Variablesyfuncionesquepuedenserusadasparamanipularelentornodeejecucin Adestacar: sys.argv:Listadecadenasquecontieneelnombredelscriptenejecucin seguidodelosparmetrosconlosquefueinvocadodichoscript. sys.exit:Funcinparaforzarlasalidadelprogramaquelainvoca. sys.stdin,sys.stdout,sys.stderr:Ficherosdeaccesoalaentrada,salidaysalida deerroresestndarrespectivamente

AdministracinyServiciosdelSO(II)
import sys import os import datetime if not os.path.isdir('log'): os.mkdir('log') log = open('log'+os.sep+'log'+datetime.datetime.now().isoformat(),'w') for root, dir, files in os.walk(sys.argv[1]): for name in files: ruta = os.path.join(root,name) tamano = os.path.getsize(ruta) if tamano > int(sys.argv[2]): log.write('El archivo: %s ocupa mas de %s bytes\n' % (ruta, sys.argv[2])) log.close()

ExpresionesRegulares
Algunagente,alconfrontarunproblema,piensa:'Yase!,Usareexpresiones regulares'.Ahoratienendosproblemas JamieZawinski,encomp.lang.emacs Pythonproveedelmdulo're'paralaaplicacindeexpresionesregulares.La sintaxisparaladefinicindeexpresionesregularesessimilaralausadaenPerl. Con're'podemosversiunacadenaseajustaaunpatrn,sicontienedichopatrn, etc... LaspeculiaridadqueaadePythonenestesentidoeslaposibilidadde'compilar' unaexpresinregularparadespuspoderaplicarlaamltiplescadenas
>> import re >> emails = re.compile('^[0-9a-zA-Z\.\-\_]+@[[0-9a-zA-Z\.\-\_]+\.[a-zA-Z]{2,3}$') >> if emails.match('new_user@subhost.host77.com'): >> print 'valido' valido >> if emails.match('user!!@host.c'): >> print 'valido' .. >>

ProtocolosdeRed(I)
Ensulibreraestndar,Pythonproveedemdulosparatrabajarconftp,web, sockets,pop...amuyaltonivel,actuandotantodeclientecomodeservidor
import urllib, re url = 'http://buscon.rae.es/draeI/SrvltGUIBusUsual?TIPO_HTML=2&LEMA=' def buscon(busqueda): datos = urllib.urlopen(url+busqueda).read() print re.sub("<[^<>]*>",'',datos)

BasadoenelbashscriptdraeporJavierCarranza
import ftplib ftp = ftplib.FTP("ftp.host.com") ftp.login(username, password) ftp.cwd(directory) ftp.retrbinary('RETR '+filename, open(filename,'wb').write) ftp.storbinary('STOR '+filename, open(filename,'rb'))

ProtocolosdeRed(II)
import SocketServer class MyHandler(SocketServer.BaseRequestHandler): def handle(self): while 1: dataReceived = self.request.recv(1024) self.request.send(dataReceived) myServer = SocketServer.ThreadingTCPServer(('',8881), MyHandler) myServer.serve_forever( )

ExtraidodeO'ReillyPythonCookbook

ProgramacinDistribuida
Paralasllamadasaprocedimientoremoto,usadasparacomunicarprocesosque correnendistintasmquinas,Pythonproveeensulibreraestndardeinterfaza XMLRPC,aunqueexistenalternativasfueradelalibreracomoSOAPoCORBA
import SimpleXMLRPCServer class holamundo: def hola(self): return 'hola mundo!!' server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost',8080)) server.register_instance(archivoRemoto()) server.serve_forever() >> import xmlrpclib >> server = xmlrpclib.ServerProxy('http://localhost:8080') >> print server.hola() hola mundo !!

Frameworks

Twisted
Twistedesunframeworkdedesarrollodeaplicacionesdered. Permiterealizaroperacionestantoabajonivelconsocketscomoaaltonivel,hasta talpuntoquecontieneservidoresweb,chat,decorreo,etc...yaprogramadosy listosparauseroadaptaralasnecesidadesdelaaplicacinderednecesitada. ConTwistedpodeistambincrearvuestrospropiosprotocolosdered. Laprogramacindeestosesmuysencillaytodoelloenelparadigmaorientado aobjetoenPython

TurboGears
TurboGearsesunframeworkdedesarrollorpidodeaplicacionesweb. EstbasadoenelpatrnModelViewController,y haceusodeunaseriedecomponentes independientesparaundesarrolloFronttoBack

Mochikit:LimpiaypotentelibreraJavascript Kid:Sistemadeplantillas CherryPy:Hacequeprogramarlaentrada/salida delawebseatanfcilcomocrearfunciones python SqlObject:Transformaaclaseslastablasdetu basededatos.

Pygame
Pygameesunframeworkmultiplataformadiseadoparalafcilprogramacinde softwaremultimedia,comoporejemplojuegos,enPython.Pygamerequierela bibliotecamultimediaSDLparafuncionar.
import sys, pygame pygame.init() size = width, height = 640, 480 speed = [2, 2] white = 255,255,255 screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.bmp") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(white) screen.blit(ball, ballrect) pygame.display.flip()

wxPython
ExistendiversoswrappersdeguitoolkitsparaPython,entreellospythonqt,python gtk,oTkinter.Enestapresentacinnoscentraremosen,quizs,elmsexitosode ellos:wxPython Caractersticas:

BindingdewxWidgets Multiplataforma Utilizaelsetdewidgetnativodelaplataformasobrelaquecorra Sencillezdeuso Fcildecreartuspropioswidgets

Bibliografa

O'ReillyPythonCookbook O'ReillyPythonStandardLibrary O'ReillyPythonAdvancedProgramming ManningwxPythonInAction GuadeAprendizajePythondeGuidoVanRossum www.python.org www.pygame.org www.turbogears.org www.twistedmatrix.com www.wxpython.org

EstapresentacinsedistribuyeconlalicenciaCreativeCommonsquesigue: http://creativecommons.org/licenses/byncsa/2.5/es/

You might also like