Python avanzado - parte 1

676 views

Published on

Primera parte de una serie de Charlas de Python Avanzado.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Python avanzado - parte 1

  1. 1. Avanzado Parte I Wednesday, January 30, 13
  2. 2. El Charlista Wednesday, January 30, 13
  3. 3. @coto Wednesday, January 30, 13
  4. 4. @coto Wednesday, January 30, 13
  5. 5. Mobile Framework JavaScript (2010) Wednesday, January 30, 13
  6. 6. Mobile Framework JavaScript (2010) Wednesday, January 30, 13
  7. 7. Wednesday, January 30, 13
  8. 8. Wednesday, January 30, 13
  9. 9. Wednesday, January 30, 13
  10. 10. Wednesday, January 30, 13
  11. 11. coto@cotos-pro ~ 02:15 > python Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> Wednesday, January 30, 13
  12. 12. Iniciar Python coto@cotos-pro ~ 02:15 > python Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> Wednesday, January 30, 13
  13. 13. • Los programas se ejecutan hasta que se alcanza EOF • Con Control-D o Control-Z en el símbolo de sistema • o escribe: raise SystemExit Wednesday, January 30, 13
  14. 14. Terminar Python • Los programas se ejecutan hasta que se alcanza EOF • Con Control-D o Control-Z en el símbolo de sistema • o escribe: raise SystemExit Wednesday, January 30, 13
  15. 15. #!/usr/bin/env python print "Hello World" Wednesday, January 30, 13
  16. 16. El truco del #! #!/usr/bin/env python print "Hello World" Wednesday, January 30, 13
  17. 17. El truco del #! #!/usr/bin/env python print "Hello World" > python archivo.py Wednesday, January 30, 13
  18. 18. El truco del #! #!/usr/bin/env python print "Hello World" Wednesday, January 30, 13
  19. 19. El truco del #! #!/usr/bin/env python print "Hello World" > chmod +x archivo.py > ./archivo.py Wednesday, January 30, 13
  20. 20. >>> # suma ... 3+5 8 >>> # resta ... 3-4 -1 >>> # multiplicacion ... 2.0*3 6.0 Wednesday, January 30, 13
  21. 21. Operadores >>> # suma ... 3+5 8 >>> # resta ... 3-4 -1 >>> # multiplicacion ... 2.0*3 6.0 Wednesday, January 30, 13
  22. 22. >>> # division ... 3/2 1.5 >>> # cociente ... 3//2 1 >>> # resto ... 3%2 1 Wednesday, January 30, 13
  23. 23. Operadores >>> # division ... 3/2 1.5 >>> # cociente ... 3//2 1 >>> # resto ... 3%2 1 Wednesday, January 30, 13
  24. 24. >>> # potencia ... 3**2 9 >>> # left shift ... 5<<2 20 >>> # right shift ... 5>>2 1 Wednesday, January 30, 13
  25. 25. Operadores >>> # potencia ... 3**2 9 >>> # left shift ... 5<<2 20 >>> # right shift ... 5>>2 1 Wednesday, January 30, 13
  26. 26. >>> # el operador ternario ?: ... ( 5 > 2 ) and “a” or “b” Wednesday, January 30, 13
  27. 27. Operadores >>> # el operador ternario ?: ... ( 5 > 2 ) and “a” or “b” Wednesday, January 30, 13
  28. 28. Operadores >>> # el operador ternario ?: ... ( 5 > 2 ) and “a” or “b” “a” Wednesday, January 30, 13
  29. 29. Operadores >>> # el operador ternario ?: ... ( 5 > 2 ) and “a” or “b” “a” >>> "a" if ( 5 > 2 ) else "b" “a” Wednesday, January 30, 13
  30. 30. a b c d e = = = = = [2, [2, [] [2, a + 3, 4] 7, 3.5, "Hello"] [a,b]] b # # # # # list de enteros lista mixta lista vacia Lista con otra lista Unir dos listas # # # # Obtén el 2º elemento Obtén una sublista Listas anidadas Cambiar un elemento Manipulando Listas x = a[1] y = b[1:3] z = d[1][0][2] b[0] = 42 Wednesday, January 30, 13
  31. 31. Listas a b c d e = = = = = [2, [2, [] [2, a + 3, 4] 7, 3.5, "Hello"] [a,b]] b # # # # # list de enteros lista mixta lista vacia Lista con otra lista Unir dos listas # # # # Obtén el 2º elemento Obtén una sublista Listas anidadas Cambiar un elemento Manipulando Listas x = a[1] y = b[1:3] z = d[1][0][2] b[0] = 42 Wednesday, January 30, 13
  32. 32. f = (2,3,4,5) g = (,) h = (2, [3,4], (10,11,12)) # tupla de enteros # tupla vacia # tupla mixta Manipulando Tuplas x = f[1] y = f[1:3] z = h[1][1] Wednesday, January 30, 13 # Obtén el 2º elemento # Obtén una porción # Agrupamiento
  33. 33. Tuplas f = (2,3,4,5) g = (,) h = (2, [3,4], (10,11,12)) # tupla de enteros # tupla vacia # tupla mixta Manipulando Tuplas x = f[1] y = f[1:3] z = h[1][1] Wednesday, January 30, 13 # Obtén el 2º elemento # Obtén una porción # Agrupamiento
  34. 34. Tuplas f = (2,3,4,5) g = (,) h = (2, [3,4], (10,11,12)) # tupla de enteros # tupla vacia # tupla mixta Manipulando Tuplas x = f[1] y = f[1:3] z = h[1][1] # Obtén el 2º elemento # Obtén una porción # Agrupamiento • Las tuplas son como las listas, pero con tamaño definido. • No se pueden reemplazar miembros. Wednesday, January 30, 13
  35. 35. a = { } b = { ’x’: 3, ’y’: 4 } c = { ’uid’: 105, ’login’: ’beazley’, ’name’ : ’David Beazley’ } Acceso a diccionarios u = c[’uid’] c[’shell’] = "/bin/sh" “name” in c c.get(“name”, “no value”) Wednesday, January 30, 13 # # # # Acceso a un elemento Crear elemento Chequear elemento Chequear elemento
  36. 36. Diccionarios a = { } b = { ’x’: 3, ’y’: 4 } c = { ’uid’: 105, ’login’: ’beazley’, ’name’ : ’David Beazley’ } Acceso a diccionarios u = c[’uid’] c[’shell’] = "/bin/sh" “name” in c c.get(“name”, “no value”) Wednesday, January 30, 13 # # # # Acceso a un elemento Crear elemento Chequear elemento Chequear elemento
  37. 37. lambda arguments: expression def name(arguments): return expression > f = lambda x, y : x + y > f(1,1) 2 Wednesday, January 30, 13
  38. 38. Lambdas y Func. Prog. lambda arguments: expression def name(arguments): return expression > f = lambda x, y : x + y > f(1,1) 2 Wednesday, January 30, 13
  39. 39. > foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] > print map(lambda x: x * 2 + 10, foo) ...[14, 46, 28, 54, 44, 58, 26, 34, 64] > foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> print filter(lambda x: x % 3 == 0, foo) ...[18, 9, 24, 12, 27] > foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> print reduce(lambda x, y: x + y, foo) ...139 Wednesday, January 30, 13
  40. 40. Lambdas y Func. Prog. > foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] > print map(lambda x: x * 2 + 10, foo) ...[14, 46, 28, 54, 44, 58, 26, 34, 64] > foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> print filter(lambda x: x % 3 == 0, foo) ...[18, 9, 24, 12, 27] > foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> print reduce(lambda x, y: x + y, foo) ...139 Wednesday, January 30, 13
  41. 41. #!/usr/bin/env python def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold @makeitalic def hello(): return "hello world" print hello() ## returns <b><i>hello world</i></b> Wednesday, January 30, 13
  42. 42. Decorators #!/usr/bin/env python def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold @makeitalic def hello(): return "hello world" print hello() ## returns <b><i>hello world</i></b> Wednesday, January 30, 13
  43. 43. class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt def withdraw(self,amt): self.balance = self.balance - amt def getbalance(self): return self.balance Wednesday, January 30, 13
  44. 44. Classes class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt def withdraw(self,amt): self.balance = self.balance - amt def getbalance(self): return self.balance Wednesday, January 30, 13
  45. 45. a = Account(1000.00) a.deposit(550.23) a.deposit(100) a.withdraw(50) print a.getbalance() Wednesday, January 30, 13
  46. 46. Classes a = Account(1000.00) a.deposit(550.23) a.deposit(100) a.withdraw(50) print a.getbalance() Wednesday, January 30, 13
  47. 47. Classes a = Account(1000.00) a.deposit(550.23) a.deposit(100) a.withdraw(50) print a.getbalance() Wednesday, January 30, 13
  48. 48. class Electricity(object): ! """Describe the electricity""" def __init__(self): # the self variable represents the instance of the object itself. # Constructor for instances, it will overwrite Class attributes # when it is called self._private = 'inside' self._voltage = 220   @property def voltage(self): return self._voltage   @voltage.setter def voltage(self, value): self._voltage = value/2   _private = 'outside' _another_private = 'boo' @voltage.deleter def voltage(self): del self._voltage   @staticmethod def metodo_estatico(val1, val2): return "Hello %s and %s" % (val1, val2)   @classmethod def metodo_class(cls, val2): return "Hello %s and %s" % (cls, val2) Wednesday, January 30, 13
  49. 49. Classes class Electricity(object): ! """Describe the electricity""" def __init__(self): # the self variable represents the instance of the object itself. # Constructor for instances, it will overwrite Class attributes # when it is called self._private = 'inside' self._voltage = 220   @property def voltage(self): return self._voltage   @voltage.setter def voltage(self, value): self._voltage = value/2   _private = 'outside' _another_private = 'boo' @voltage.deleter def voltage(self): del self._voltage   @staticmethod def metodo_estatico(val1, val2): return "Hello %s and %s" % (val1, val2)   @classmethod def metodo_class(cls, val2): return "Hello %s and %s" % (cls, val2) Wednesday, January 30, 13
  50. 50. try: f = open("foo") except IOError, e: print "Couldn’t open ’foo’. Error: {}".format(e) try: f = open("foo") except Exception: print "Couldn’t open ’foo’. Sorry." Wednesday, January 30, 13
  51. 51. Exceptions try: f = open("foo") except IOError, e: print "Couldn’t open ’foo’. Error: {}".format(e) try: f = open("foo") except Exception: print "Couldn’t open ’foo’. Sorry." Wednesday, January 30, 13
  52. 52. import re r = re.compile(r’(d+).(d*)’) m = r.match("42.37") a = m.group(0) # Returns ’42.37’ b = m.group(1) # Returns ’42’ c = m.group(2) # Returns ’37’ print m.start(2) # Prints 3 Wednesday, January 30, 13
  53. 53. Expresiones Regulares import re r = re.compile(r’(d+).(d*)’) m = r.match("42.37") a = m.group(0) # Returns ’42.37’ b = m.group(1) # Returns ’42’ c = m.group(2) # Returns ’37’ print m.start(2) # Prints 3 Wednesday, January 30, 13
  54. 54. • • • • • • • Seguridad en Python Interfaces de Sistema Operativo Trabajando con Threads Programando en Red Interfaces de Base de Datos Ejecución restringida Extensiones en C Wednesday, January 30, 13
  55. 55. Próximamente... • • • • • • • Seguridad en Python Interfaces de Sistema Operativo Trabajando con Threads Programando en Red Interfaces de Base de Datos Ejecución restringida Extensiones en C Wednesday, January 30, 13
  56. 56. Gracias!! @coto Wednesday, January 30, 13

×