Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/python-functions-and-classes.tex
blob: a7210600d98538123ee61f573636e925bc109946 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
\mode* % Reset \mode<all> from slides.tex

\section{\en{Functions}\es{Funciones}}

\note{Before starting, ask how everyone got on with the exercises from part 1.}

\en{We've already seen how to call existing functions; now we'll see how to
define new ones. As with loops and conditionals, a function is a block of code
which is indented by 4 spaces relative to the name of the function, which is
itself preceded by \texttt{def} and followed by a list of parameter names. These
parameter names become variables in your function's code, with values provided
by the caller of the function.}
\es{Ya hemos visto cómo llamar a las funciones existentes, ahora veremos cómo
definir otros nuevos. Al igual que con los bucles y condicionales, una función
es un bloque de código que está sangrado por 4 espacios relativos al nombre de
la función, que es sí precidido por \texttt{def} y seguido por una lista de
nombres de parametros. Estos nombres de parametros se convierten en variables en
el código de su función, con los valores previstos por el llamador de la
función.}

\begin{frame}[fragile]
\frametitle{\en{Functions}\es{Funciones}}
\begin{lstlisting}[language=Python]
def funcion_sin_parametros():
    print('Este funcion no tiene parametros')

def funcion_con_parametros(para1, para2):
    print('Este funcion tiene parametros: %s y %s' % (para1, para2))

# Llame a los funciones.
funcion_sin_parametros()
funcion_con_parametros('hola', 'mundo')
\end{lstlisting}
\end{frame}

\en{In the previous example, neither function returned a value. To do this, use
the \texttt{return} statement. As soon as this statement is executed, control
will return to the code which called the function --- so code after the
\texttt{return} statement will not be executed. The following example
demonstrates a function which returns the minimum of its two parameters.}
\es{En el ejemplo anterior, ni la función devuelve un valor. Para ello, utilice
la instrucción \texttt{return}. Tan pronto como se ejecuta esta instrucción, el
control volverá al código que llama a la función --- no se ejecute código
después de la instrucción \texttt{return}. El ejemplo
siguiente demuestra una función que devuelve el mínimo de sus dos parametros.}

\begin{frame}[fragile]
\frametitle{\en{Functions}\es{Funciones}}
\begin{lstlisting}[language=Python]
def min(numero_a, numero_b):
    if numero_a > numero_b:
        return numero_b
    else:
        return numero_a

minimo = min(5, 7)
print('El numero mas pequeno es %i' % minimo)
\end{lstlisting}
\end{frame}

\en{You can think of this as substituting the parameters from the function call
into the function's code, and then substituting that for the return value of the
function call.}
\es{Ustedes pueden pensar en este como la sustitución de los parámetros de la
llamada a la función en el código de la función, y después la sustitución de
este al valor de retorno de la llamada de función.}

\begin{frame}[fragile]
\frametitle{\en{Functions}\es{Funciones}}
\begin{lstlisting}[language=Python]
minimo = (
    if 5 > 7:
        return 7
    else:
        return 5
)
print('El numero mas pequeno es %i' % minimo)
\end{lstlisting}
\end{frame}

\subsection{\en{Recursion}\es{Recursividad}}

\en{Functions allow for a new type of control flow: they allow for
\emph{recursion}. Recursion is where a function calls itself and uses the return
value from the call in its calculation. A typical example of this is in
computing mathematical factorials. It's possible to implement this calculation
using a loop, but it's more natural to implement using recursion, as this
mirrors the mathematical definition of factorials.}
\es{Funciones permiten un nuevo tipo de flujo de control: que permiten
recursividad. La recursividad es que una función llama a sí mismo y utiliza el
valor de retorno de la llamada en su cálculo. Un ejemplo típico de esto es en
el cálculo de factoriales matemáticos. Es posible implementar este cálculo
usando un bucle, pero es más natural para implementar con la recursividad, ya
que esto refleja la definición matemática de los factoriales.}

\en{As with \texttt{while} loops, ensure your recursion always terminates, or
you will get an infinite recursion, like an infinite loop.}
\es{Al igual que con bucles \texttt{while}, asegúrese de que su recursividad
siempre termina o obtendrá una recursividad infinita, como un bucle infinito.}

\begin{frame}[fragile]
\frametitle{\en{Recursion}\es{Recursividad}}
\begin{lstlisting}[language=Python]
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

# factorial(n)
#   == n * factorial(n - 1)
#   == n * (n - 1) * factorial(n - 2)
#   ...
#   == n * (n - 1) * ... * 1
\end{lstlisting}
\end{frame}

\note{Demonstrate this by adding a trace \texttt{print()} statement at the top
      of \texttt{factorial()}.}


\section{\en{Imports}\es{Importaciónes}}

\en{Python provides a large number of existing functions, with related functions
grouped together in \emph{modules}. To speed up loading of programs, only the
functions from modules which your program \emph{imports} explicitly are
available to call.}
\es{Python tiene un gran número de funciónes existentes, con funcionadas
relacionadas agrupados en \emph{módulos}. Para acelerar la carga de los
programas, sólo las funciones de los módulos que el programa ha \emph{importado}
expresamente están disponibles para llamar.}

\en{To import a module, use the \texttt{import} statement at the top of your
Python file. Common modules which you might want to import are:}
\es{Para importar un módulo, utilice la instrucción \texttt{import} al principio
de su archivo de Python. Módulos comunes que es posible que desee importar son:}
\begin{description}
    \item[\texttt{os}]
        {\en{Functions for interfacing with the operating system.}
         \es{Funciones para la interfaz con el sistema operativo.}}
    \item[\texttt{sys}]
        {\en{Functions for interfacing with the Python interpreter.}
         \es{Funciones para la interfaz con el intérprete de Python.}}
    \item[\texttt{math}]
        {\en{Mathematical functions more advanced than simple arithmetic.}
         \es{Funciones matemáticas más avanzadas que simple aritmética.}}
    \item[\texttt{gi.repository.Gtk}]
        {\en{Graphical user interface classes and functions from GTK+.}
         \es{Funciones de la interfaz gráfica de usario y clases de GTK+.}}
\end{description}

\begin{frame}[fragile]
\frametitle{\en{Imports}\es{Importaciónes}}
\begin{lstlisting}[language=Python]]
#!/usr/bin/python
# coding=utf-8

import os
import math
from gi.repository import Gtk
from sys import argv
\end{lstlisting}
\end{frame}

\note{Demonstrate this in the interpreter by calling \texttt{math.sin()} before
      and after \texttt{import~python}.}

\en{Python modules can be arranged in hierarchies, with the modules named after
the files and directories which contain the code. For example,
\texttt{repository} is a sub-module of \texttt{gi}. When referencing a class
or method in code, you can include the name of the sub-module containing it if
that sub-module hasn't been imported already (but its parent module has).}
\es{Módulos de Python se pueden organizar en jerarquías, con los módulos llevan
el nombre de los archivos y directorios que contienen el código. Para ejemplo,
\texttt{repository} es un sub-módulo de \texttt{gi}. Al hacer referencia a un
clase o un método en el código, se pueden incluir el nombre de el sub-módulo que
lo contiene él, si ese sub-módulo no se ha importado ya (pero su módulo padre
ha).}


\section{\en{Classes}\es{Clases}}

\en{A \emph{class} is a collection of functions and variables which can be
instantiated multiple times. Each instance of a class is an \emph{object} and
its variables are separate from those of other instances of the same class.}
\es{Una clase es una colleción de funciones y variables que se puede crear
instancias múltiplas veces. Cada instancia de una clase es objecto y sus
variables son independientes de los otra instancias de la misma clase.}

\en{Why collect functions and variables together? It makes maintaining a large
program a lot easier by separating code and data out into different components
which don't interfere with each other. You can think of a class as describing
a single real-world object, such as a vehicle or a table. All the state
(variables) associated with that object is in the class, and all the actions
which can be performed on that object are declared as methods (functions) of the
class. Classes don't \emph{always} correspond to real-world objects, but the
principle stands.}
\es{¿Por qué recoger las funciones y variables en conjunto? Esto hace que el
mantenimiento de un gran programa mucho más fácil mediante de las separación de
código y datos a cabo en diferentes componentes que no interfieren entre sí.
Ustedes pueden pensar en una clasa como la descripción de un objeto de mundo
real, tales como un vehículo o una mesa. Todo el estado (variables) asociada a
ese objeto se encuentra en la clase, y todas las acciones que se pueden realizar
en ese objeto se declaran como métodos (funciones) de la clase. Las clases no
siempre corresponden a las objetos del mundo real, pero el principio sigue en
pie.}

\en{To define a class in Python, use the \texttt{class} statement, followed by
the class name, then the name of its parent class in brackets. All code inside
the class must be indented by 4 spaces. Parent classes allow for inheritance,
which is covered shortly.}
\es{Para definir una clase en Python, utilice la instrucción \texttt{class},
seguido por el nombre de la clase, después el nombre de su clase padre entre
paréntesis. Todo el código dentre de la clase debe tener una sangría de 4
espacios. Clases de padres permiten herencia, que se cubrirá pronto.}

\en{In this example, the \texttt{Vehiculo} class has two instance variables
(\texttt{matricula} and \texttt{ruedas}) and three methods
(\texttt{\_\_init\_\_}, \texttt{calcular\_impuesto} and
\texttt{dar\_matricula}). All of the methods can access the values of the
instance variables, which can be unique for each instance of the class.}
\es{En este ejemplo, la clase \texttt{Vehiculo} tiene dos variables de instancia
(\texttt{matricula} y \texttt{ruedas}) y tres métodos (\texttt{\_\_init\_\_},
\texttt{calcular\_impuesto} and \texttt{dar\_matricula}). Todos los métodos
pueden accesar los valores de los variables de instancia, que pueden ser único
para cada instancia de la clase.}

\en{The \texttt{\_\_init\_\_} method is special: it's the \emph{constructor}
for the class. It is called when an instance of the class is created, as shown
next.}
\es{El método \texttt{\_\_init\_\_} es especial: es el \emph{constructor} de la
clase. Se llama cuando se crea una instancia de la clase, como se muestra
siguiente.}

\en{Every method in a class must have \texttt{self} as its first
parameter --- this is what makes it a \emph{method}, rather than a
\emph{function}. \texttt{self} is a reference to the object the method is being
called on, and permits access to the object's variables and other methods. To
refer to a variable or method in an instance of a class, use \texttt{self} and
a dot followed by the variable or method name.}
\es{Cada método de una clase debe tener \texttt{self} como primer
parámetro --- esto distingue métodos de funciones. \texttt{self} es una
referencia a objeto en el que se está llamando el método, y permite el acceso a
las variables y otros métodos del objeto. Para hacer referencia a una variable o
método en una instancia de una clase, utilice \texttt{self} y un punto seguido
del nombre de la variable o método.}

\begin{frame}[fragile]
\frametitle{\en{Defining classes}\es{Definición de clases}}
\begin{lstlisting}[language=Python]
class Vehiculo(object):
    def __init__(self, matricula, ruedas):
        self._matricula = matricula
        self._ruedas = ruedas

    # Asumir vehiculos estan gravados por
    # el numero de ruedas.
    def calcular_impuesto(self):
        return 100 * self._ruedas

    def dar_matricula(self):
        return self._matricula
\end{lstlisting}
\end{frame}

\en{Instantiating a class is similar to calling a function; you're effectively
calling the \texttt{\_\_init\_\_} function, and can pass it parameters as
normal. It returns an instance of the class (an object). Once you've
instantiated a class, you can call its methods using a dot --- just like calling
\texttt{append()} on a list. All lists are actually instances of a \texttt{list}
class.}
\es{Crear instancias de una clase es similar como llamado una función; estás
effectivamente llamar a la función \texttt{\_\_init\_\_}, y puede pasar
parámetros de forma normal. Élla devuelve una instancia de la clase (un objeto).
Cuando haya instanciado una clase, puede llamar a los métodos utilizando un
punto --- como llamar \texttt{append()} en una lista. Todas las listas son en
realidad instancias de una clase \texttt{list}.}

\begin{frame}[fragile]
\frametitle{\en{Using classes}\es{Utilización de clases}}
\begin{lstlisting}[language=Python]
mi_coche = Vehiculo('AB99BA', 4)
mi_moto = Vehiculo('CB21TA', 2)

print(mi_coche.calcular_impuesto())  # da 400
print(mi_coche.dar_matricula()) # da 'AB99BA'
print(mi_moto.calcular_impuesto())  # da 200
\end{lstlisting}
\end{frame}

\en{Inheritance is a major feature of classes. A class can specify a parent
class which it \emph{inherits} methods from. This means that, in the example
here, instances of the \texttt{Coche} class (which inherits from
\texttt{Vehiculo}) have \texttt{calcular\_impuesto()} and
\texttt{dar\_matricula()} methods. At the bottom of the inheritance tree is
\texttt{object}.}
\es{La herencia es una de las principales características de las clases. Una
clase puede especificar una clase padre de la que hereda métodos. Esto significa
que, en este ejemplo, instancias de la clase \texttt{Coche} (que hereda de
\texttt{Vehiculo}) tienen \texttt{calcular\_impuesto()} y
\texttt{dar\_matricula()} métodos. En la parte inferior del árbol de herencia es
\texttt{objeto}.}

\en{A child class can override one of its parent class' methods by defining
its own method of the same name. This is commonly done with the
\texttt{\_\_init\_\_} method, as here. The new code in the child class' method
can call the old code in the parent class by using \texttt{super()}.}
\es{Una clase hija puede anular uno de los métodos de su clase padre mediante
la definición de su propio método con el mismo nombre. Esto es común para el
método \texttt{\_\_init\_\_}, como se ve aquí. El nuevo código del método de la
clase hijo puede llamar al código antiguo de la clase padre mediante el uso de
\texttt{super()}.}

\begin{frame}[fragile]
\frametitle{\en{Defining classes}\es{Definición de clases}}
% Note: I've taken the liberty of using 2-space indents here to get everything
% to fit on the slide. I'm sorry.
\begin{lstlisting}[language=Python]
class Coche(Vehiculo):
  def __init__(self, matricula, peso):
    # Todos los coches tienen 4 ruedas.
    super(Coche, self).__init__(matricula, 4)
    self._peso = peso

  def calcular_presion(self):
    return self._peso / 4

class Moto(Vehiculo):
  def __init__(self, matricula):
    # Todos los motos tienen 2 ruedas.
    super(Moto, self).__init__(matricula, 2)
\end{lstlisting}
\end{frame}

\note{Demonstrate in the interpreter what happens when \texttt{self} is omitted
      from the parameter list of \texttt{\_\_init\_\_()}.}

\begin{frame}[fragile]
\frametitle{\en{Defining classes}\es{Definición de clases}}
\begin{lstlisting}[language=Python]
mi_coche = Coche('AB99BA', 1500)
mi_moto = Moto('CB21TA')

print(mi_coche.calcular_impuesto())  # da 400
print(mi_coche.dar_matricula()) # da 'AB99BA'
print(mi_moto.calcular_impuesto())  # da 200
\end{lstlisting}
\end{frame}


\subsection{\en{Private methods}\es{Métodos privados}}

\en{What if you want to define a method in your class but don't want it to be
callable from outside the class? For example, a method which performs part of a
larger calculation. The convention in Python is to prefix the method name with
a double-underscore, which hides it from code outside the class. The method is
then called a \emph{private method}. The same is true for variables, although
a single-underscore is commonly used for them.}
\es{¿Y si se quiere definir un método en la clase, pero no quiere que sea
llamable desde fuera la clase? Por ejemplo, un método que realiza parte de un
calculo más grande. La convención en Python es el prefijo del nombre del método
con un doble subrayado, que esconde de código fuera de la clase. El método se
llama entonces un método privado. Lo mismo es cierto para las variables, aunque
una sola-subrayado se utiliza comúnmente para ellos.}

\en{In this example, \texttt{\_\_agregar\_combustible()} is a private method,
and \texttt{\_combustible} and \texttt{\_cuentakilometros} are private
variables. \texttt{repostar()} is a \emph{public} method which calls
\texttt{\_\_agregar\_combustible()}. Why not put the code from
\texttt{\_\_agregar\_combustible()} into
\texttt{repostar()}? Because there may be other methods in the class which cause
fuel to be added to the car, and we want to re-use the code to do so.}
\es{En este ejemplo, \texttt{\_\_agregar\_combustible()} es un método privado, y
\texttt{\_combustible} y \texttt{\_cuentakilometros} son variables privadas.
\texttt{repostar()} es un método público que se llama
\texttt{\_\_agregar\_combustible()}. ¿Por qué no poner el código de
\texttt{\_\_agregar\_combustible()} en \texttt{repostar()}? Porque que puede
haber otros métodos en la clase que causan combustible que se añade al coche, y
queremos volver el código para hacerlo.}

\begin{frame}[fragile]
\frametitle{\en{Private methods}\es{Métodos privados}}
% Again, I've taken the liberty of using 3-space indents here to make everything
% fit.
\begin{lstlisting}[language=Python]
class Coche(Vehiculo):
   def __agregar_combustible(self, cantidad):
      self._combustible += cantidad

   def repostar(self, cantidad):
      self.__agregar_combustible(cantidad)
      self._cuentakilometros = 0
\end{lstlisting}
\end{frame}

\note{Demonstrate in the interpreter by creating a class with a public method
      and a private method, instantiating the class, and then attempting to call
      the two methods. This will show the error when calling a private method.
      Also include a call to the private method from within the class, for
      comparison.}


\subsection{\en{Properties}\es{Propiedades}}

\en{Often, it is helpful to have a public variable on a class which can be
read and written to by other code. However, it is also often necessary to
execute some code in the class when the variable is written to (for example, to
update other state in the class which depends on that variable, or to check the
new value is acceptable). Python has \emph{properties} for this, which are a
special way of handling variables in a class.}
\es{A menudo, es útil tener una variable pública en una clase que puede ser
leída y escrita por otro código. Pero también es a menudo necesaria para
ejecutar un código en la clase cuando la variable se escribe (por ejemplo,
para actualizar otro estado en la clase que depende de esa variable, o para
comprobar el nuevo valor es aceptable). Python tiene \emph{propiedades} para
esto, que son una forma especial de manejo de las variables en una clase.}

\begin{frame}[fragile]
\frametitle{\en{Properties}\es{Propiedades}}
\begin{lstlisting}[language=Python]
class Vehiculo(object):
    pasajeros = 0

mi_coche = Vehiculo()
print(mi_coche.pasajeros)  # imprime '0'
mi_coche.pasajeros = 1
\end{lstlisting}
\end{frame}

\en{Instead of defining the variable by assigning to it, as in the first
example, assign the result of the special \texttt{property()} function to it
instead. The \texttt{property()} function takes the name of a ``getter'' and a
``setter'' method as its parameters: these are called when the property is
read or written, respectively.}
\es{En lugar de definir la variable mediante la asignación de misma, como en el
primero ejemplo, asignar el resultado de la función especial \texttt{property()}
para que en su lugar. La función \texttt{property()} toma el nombre de un
método ``getter'' y un método ``setter'' como sus parámetros: estos son llamados
cuando la propiedad se lee o se escribe respectivamente.}

\begin{frame}[fragile]
\frametitle{\en{Properties}\es{Propiedades}}
\begin{lstlisting}[language=Python]
class Vehiculo(object):
    def __init__(self, escanos):
        self._pasajeros = 0
        self._escanos = escanos

    def get_pasajeros(self):
        return self._pasajeros

    def set_pasajeros(self, valor):
        if valor <= self._escanos:
            self._pasajeros = valor
        else:
            print('Demasiados pasajeros!')

    # Propiedad
    pasajeros = property(get_pasajeros,
                         set_pasajeros)
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
\frametitle{\en{Properties}\es{Propiedades}}
\begin{lstlisting}[language=Python]
mi_coche = Vehiculo(5)  # 5 escanos
mi_coche.pasajeros = 3
print(mi_coche.pasajeros)  # imprime '3'
mi_coche.pasajeros = 6 # imprime 'Demasiados'
\end{lstlisting}
\end{frame}


\section{\en{Documentation}\es{Documentación}}

\en{As mentioned before, commenting a program is vital. Python encourages this
by making class and method documentation available when running a program, if
the documentation is written in ``docstring'' format. Documentation in this
format must be written as a single string as the first line of the class or
method being documented.}
\es{Como se mencionó antes, al comentar un programa es vital. Python alienta a
esta lista la documentación de clases y métodos disponibles cuando se ejecuta
un program, si la documentación está escrita en formato ``docstring''. La
documentación en este formato debe ser escrito en una sola cadena como la
primera línea de la clase o método que se está documentando.}

\begin{frame}[fragile]
\frametitle{\en{Documentation}\es{Documentación}}
\begin{lstlisting}[language=Python]
class Vehiculo(object):
    """Un vehiculo generico.

    Esto puede repostar, guardar la distancia
    recorrida por el vehiculo, y contar el
    numero de pasajes.
    """
    def repostar(self, cantidad):
        """Anadir cantidad litros de
        combustible para el vehiculo."""
        self._combustible += cantidad
\end{lstlisting}
\end{frame}

\en{You can access documentation from the Python interpreter by reading the
\texttt{\_\_doc\_\_} member variable of the class or method.}
\es{Puede acceder a la documentación desde el intérprete Python mediante leyendo
el variable \texttt{\_\_doc\_\_} de la clase o método.}

\begin{frame}[fragile]
\frametitle{\en{Documentation}\es{Documentación}}
\begin{lstlisting}[language=Python]
print(Vehiculo.__doc__)
print(Vehiculo.repostar.__doc__)
print(range.__doc__)
\end{lstlisting}
\end{frame}

\note{Demonstrate in the interpreter by creating a class with two methods, one
      with a correct docstring, and one with its docstring in the wrong place.
      Try printing the \texttt{\_\_doc\_\_} members of each to demonstrate the
      failure.}


\section{\en{Code formatting}\es{Formato de código}}

\en{As with documentation, consistent and clear code formatting is important in
making code readable. Python has two tools available to help checking programs
for formatting errors and other errors: \texttt{pylint} and \texttt{pep8}.}
\es{Al igual que con la documentación, formato de código consistente y clara es
importante en hacer que el código legible. Python tiene dos herramientas
disponibles para comprobar los programas por errores de formato y otros errores:
\texttt{pylint} y \texttt{pep8}.}

\en{They should be run after making large additions to the code, or before
releasing a program to others.}
\es{Se deben ejecutar después de hacer grandes adiciones al código, o antes de
publicar un programa para el público.}

\begin{frame}{\en{Code formatting}\es{Formato de código}}
\en{In a terminal:}\es{En un terminal:}
\begin{itemize}
    \item{\texttt{pylint \en{my-file.py}\es{mi-archivo.py}}}
    \item{\texttt{pep8 \en{my-file.py}\es{mi-archivo.py}}} 
\end{itemize}
\end{frame}

\note{Demonstrate with some correct and incorrect Python files.}


\section{\en{UIs with GTK+}\es{UIs con GTK+}}

\en{Creating user interfaces (UIs) will be covered in more detail in
\autoref{part:writing-sugar-activities}, but it's useful to cover a simple
example now as a demonstration of the use of classes.}
\es{Creación de interfaces de usario (UI) se tratarán en más detalle adelante,
pero es útil para examinar un ejemplo
sencillo ahora como un demonstración del uso de las clases.}

\en{In the GTK+ UI toolkit, every on-screen UI element (or \emph{widget}) is an
object --- an instance of a class. For example, there's a \texttt{Button} class
which is instantiated for every button in a program. In this example, the
\texttt{Window} and \texttt{Button} classes are instantiated to give a window
containing a button. The example is cut down to its bare minimum, and is not a
useful program.}
\es{En el conjunto de herramientas de interfaz de usario GTK+, todos los
elementos (o widgets) de interfaz en pantalla es un objeto --- una instancia de
una clase. Para ejemplo, hay una clase \texttt{Button} que se emplea para cada
botón en un programa. En este ejemplo, las clases \texttt{Window} y
\texttt{Button} se crean instancias para dar una ventana con un botón. El
ejemplo se redujo a su mínima expresión, y no es un programa útil.}

\begin{frame}{\en{UI example}\es{Ejemplo de UI}}
\begin{figure}[h!]
    \centering
    \includegraphics[width=0.5\textwidth]{simple-gtk-program.png}
    \caption{\en{The simple GTK+ program being run.}
             \es{El programa sencillo de GTK+ está trabajando.}}
    \label{fig:simple-gtk-program}
\end{figure}
\end{frame}

\begin{frame}[fragile]
\frametitle{\en{UI example}\es{Ejemplo de UI}}
\begin{lstlisting}[language=Python]
from gi.repository import Gtk

ventana = Gtk.Window(title='Hola mundo')
boton = Gtk.Button('Un boton')
ventana.add(boton)
ventana.show_all()

Gtk.main()
\end{lstlisting}
\end{frame}


\section{\en{Licencing}\es{Licencias}}

\en{An important part of the Sugar project is that it is free software --- in
the sense that anyone has the freedom to read and modify the source code. To
upload an activity to \url{http://activities.sugarlabs.org/} it must use a
free software licence. This is important, as it allows students to view and
learn from the code running their activities, and potentially modify it to
improve the activities.}
\es{Una parte importante del proyecto Sugar es que es software libre --- en el
sentido de que cualquier persona tiene la libertidad de leer y modificar el
código fuente. Para subir una actividad para
\url{http://activities.sugarlabs.org/} debe utilizar una licencia de software
libre. Esto es importante, ya que permite a los estudiantes ver y aprender del
código que se ejecuta sus actividades, y posiblemente modificarlo para mejorar
las actividades.}

\en{There are several major free software licences, and you must choose one
which matches your ideology. The most relevant three licences are: GPL, MIT and
BSD. The Sugar project itself uses GPL.}
\es{Hay varias licencias principales del software libre, y ustedes deben elegir
uno que coincida con su ideología. Las tres licencias más relevantes son: GPL,
MIT y BSD. El proyecto Sugar en sí utiliza GPL.}

\begin{frame}{\en{Licencing}\es{Licencias}}

\begin{block}{}
\url{http://gnu.org/licenses/license-recommendations.html}
\end{block}

\begin{block}{}
\begin{description}
    \item[GPL]{\url{http://\en{en}\es{es}.wikipedia.org/wiki/GPL}}
    \item[MIT]{\url{http://\en{en}\es{es}.wikipedia.org/wiki/MIT_License}}
    \item[BSD]{\url{\en{http://en.wikipedia.org/wiki/BSD_licenses}
                    \es{http://es.wikipedia.org/wiki/Licencia_BSD}}}
\end{description}
\end{block}
\end{frame}


\section{\en{Miscellany}\es{Miscelánea}}

\en{Because this is a short course, not everything can be covered. Here are the
major topics in Python which have been omitted, along with links to relevant
documentation.}
\es{Debido a que este es un curso corto, no todo puede ser cubierto. Estos son
los principales temas en Python que han sido omitidas, junto con enlaces a la
documentación pertinente.}

\begin{frame}{\en{What's missing}\es{Temas no abarcados}}
\begin{itemize}
    \item{\en{Exceptions}\es{Excepciones}:
          \en{\href{http://docs.python.org/2/tutorial/errors.html}{(1)}}
          \es{\href{http://docs.python.org.ar/tutorial/2/errors.html}{(1)}},
          \href{http://docs.python.org/2.7/library/exceptions.html}{(2)}}
    \item{\en{Lambda functions}\es{Funciones lambda}:
          \en{\href{http://docs.python.org/2.7/tutorial/controlflow.html\#lambda-forms}{(1)}}
          \es{\href{http://docs.python.org.ar/tutorial/2/controlflow.html\#formas-con-lambda}{(1)}},
          \href{http://www.diveintopython.net/power_of_introspection/lambda_functions.html}{(2)}}
    \item{\en{File I/O}\es{Entrada y salida de archivos}:
          \en{\href{http://docs.python.org/2.7/tutorial/inputoutput.html\#reading-and-writing-files}{(1)}}
          \es{\href{http://docs.python.org.ar/tutorial/2/inputoutput.html\#leyendo-y-escribiendo-archivos}{(1)}},
          \href{http://en.wikibooks.org/wiki/Python_Programming/Input_and_output}{(2)},
          \href{http://docs.python.org/2/library/pickle.html}{(3)}}
    \item{Unicode:
          \href{http://docs.python.org/2/howto/unicode.html}{(1)}}
    \item{\en{Optional and variable arguments}\es{Argumentos opcionales y variables}:
          \en{\href{http://docs.python.org/2/tutorial/controlflow.html\#more-on-defining-functions}{(1)}}
          \es{\href{http://docs.python.org.ar/tutorial/2/controlflow.html\#mas-sobre-definicion-de-funciones}{(1)}},
          \href{http://www.diveintopython.net/power_of_introspection/optional_arguments.html}{(2)}}
    \item{\en{Functional programming}\es{Programación funcional}:
          \href{http://docs.python.org/2/howto/functional.html}{(1)},
          \href{http://anandology.com/python-practice-book/functional-programming.html\#higher-order-functions-decorators}{(2)}}
    \item{\en{Multiple inheritance}\es{Herencia múltiple}:
          \en{\href{http://docs.python.org/2/tutorial/classes.html\#multiple-inheritance}{(1)}}
          \es{\href{http://docs.python.org.ar/tutorial/2/classes.html\#herencia-multiple}{(1)}}}
    \item{\en{Standard library}\es{Librería estándar}:
          \en{\href{http://docs.python.org/2/tutorial/stdlib.html}{(1)}}
          \es{\href{http://docs.python.org.ar/tutorial/2/stdlib.html}{(1)}},
          \href{http://docs.python.org/2/library/}{(2)}}
\end{itemize}
\end{frame}