Commit 2b2c0d29 authored by Mario Chirinos Colunga's avatar Mario Chirinos Colunga 💬

opp update

parent 3739c57f
......@@ -24,7 +24,9 @@
"* Interpretado (Se ejecuta sin compilación previa)\n",
"* Tipificación Dinamica (Se realiza durante en tiempo de ejecución)\n",
"* Multiparadigma\n",
"* Interactivo (con ipython)\n"
"* Interactivo (con ipython)\n",
"\n",
"*Nota: Python obtiene su nombre del programa de la BBC [Monty Python's Flying Circus](https://www.imdb.com/title/tt0063929/).*"
]
},
{
......@@ -40,7 +42,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 1,
"metadata": {},
"outputs": [
{
......@@ -49,7 +51,7 @@
"int"
]
},
"execution_count": 5,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
......@@ -60,7 +62,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 2,
"metadata": {},
"outputs": [
{
......@@ -69,7 +71,7 @@
"float"
]
},
"execution_count": 6,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
......@@ -80,7 +82,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 3,
"metadata": {},
"outputs": [
{
......@@ -89,7 +91,7 @@
"complex"
]
},
"execution_count": 7,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
......@@ -110,7 +112,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 4,
"metadata": {},
"outputs": [
{
......@@ -119,7 +121,7 @@
"list"
]
},
"execution_count": 9,
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
......@@ -130,7 +132,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 5,
"metadata": {},
"outputs": [
{
......@@ -139,7 +141,7 @@
"tuple"
]
},
"execution_count": 10,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
......@@ -150,7 +152,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 6,
"metadata": {},
"outputs": [
{
......@@ -159,13 +161,13 @@
"range"
]
},
"execution_count": 11,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
" type(range(1))"
"type(range(1))"
]
},
{
......@@ -178,7 +180,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 7,
"metadata": {},
"outputs": [
{
......@@ -187,7 +189,7 @@
"str"
]
},
"execution_count": 13,
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
......@@ -206,7 +208,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 8,
"metadata": {},
"outputs": [
{
......@@ -215,7 +217,7 @@
"dict"
]
},
"execution_count": 15,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
......@@ -235,7 +237,7 @@
},
{
"cell_type": "code",
"execution_count": 34,
"execution_count": 9,
"metadata": {},
"outputs": [
{
......@@ -244,7 +246,7 @@
"{1, 2, 3, 5, 6}"
]
},
"execution_count": 34,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
......@@ -273,7 +275,7 @@
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 10,
"metadata": {},
"outputs": [
{
......@@ -282,7 +284,7 @@
"True"
]
},
"execution_count": 16,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
......@@ -293,7 +295,7 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 11,
"metadata": {},
"outputs": [
{
......@@ -302,7 +304,7 @@
"False"
]
},
"execution_count": 18,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
......@@ -313,7 +315,7 @@
},
{
"cell_type": "code",
"execution_count": 19,
"execution_count": 12,
"metadata": {},
"outputs": [
{
......@@ -322,7 +324,7 @@
"False"
]
},
"execution_count": 19,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
......@@ -333,7 +335,7 @@
},
{
"cell_type": "code",
"execution_count": 17,
"execution_count": 13,
"metadata": {},
"outputs": [
{
......@@ -342,7 +344,7 @@
"True"
]
},
"execution_count": 17,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
......@@ -353,7 +355,7 @@
},
{
"cell_type": "code",
"execution_count": 22,
"execution_count": 14,
"metadata": {},
"outputs": [
{
......@@ -362,7 +364,7 @@
"False"
]
},
"execution_count": 22,
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
......@@ -373,7 +375,7 @@
},
{
"cell_type": "code",
"execution_count": 23,
"execution_count": 15,
"metadata": {},
"outputs": [
{
......@@ -382,7 +384,7 @@
"True"
]
},
"execution_count": 23,
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
......@@ -437,7 +439,7 @@
},
{
"cell_type": "code",
"execution_count": 36,
"execution_count": 16,
"metadata": {},
"outputs": [
{
......@@ -457,7 +459,7 @@
},
{
"cell_type": "code",
"execution_count": 38,
"execution_count": 17,
"metadata": {},
"outputs": [
{
......@@ -479,7 +481,7 @@
},
{
"cell_type": "code",
"execution_count": 42,
"execution_count": 18,
"metadata": {},
"outputs": [
{
......@@ -499,7 +501,7 @@
},
{
"cell_type": "code",
"execution_count": 44,
"execution_count": 19,
"metadata": {},
"outputs": [
{
......@@ -521,6 +523,99 @@
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"3\n",
"4\n"
]
}
],
"source": [
"for i in range(5):\n",
" if(i==2):\n",
" continue\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n"
]
}
],
"source": [
"for i in range(5):\n",
" if(i==2):\n",
" break\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"for i in range(5):\n",
" if(i==2):\n",
" pass\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5\n",
"0.6666666666666666\n",
"1.0\n",
"2.0\n",
"ERROR\n"
]
}
],
"source": [
"for i in reversed(range(5)):\n",
" try:\n",
" print(2/i)\n",
" except:\n",
" print(\"ERROR\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -535,8 +630,148 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1.4 Ejercicios\n",
"## 1.4.1 Inprimir todos los numeros pares en 0 y 20."
"## 1.4 Funciones\n",
"Una función es un conjunto de setencias que pueden ser invocadas varias veces durante la ejecución de un programa. Permiten minimizar el codigo, amuentar su legibilidad y permiten reutilizar código. En python las funciones son definida por la palabra reservada **def**. \n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World\n"
]
}
],
"source": [
"def HelloWorld():\n",
" print(\"Hello World\")\n",
"\n",
"HelloWorld()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.1 Parametros\n",
"La funciones pueden aceptar arguentos de entrada y devoler resultados."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Mario\n"
]
}
],
"source": [
"def Hello(name):\n",
" print(\"Hello \"+name)\n",
"Hello(\"Mario\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.2 Parametros Opcionales\n",
"Las funciones tampien pueden aceptar parametros opcionales, los cuales toman en valor indicado por defecto si no son pasados a la funcion."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Mario!!!\n",
"Hello Mario?\n",
"Hello Mario!\n",
"Hello Alex!!\n"
]
},
{
"data": {
"text/plain": [
"[1]"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def Hello(name, x=\"!!!\"):\n",
" print(\"Hello \" + name + x)\n",
"Hello(\"Mario\")\n",
"Hello(\"Mario\",\"?\")\n",
"Hello(x=\"!\", name=\"Mario\")\n",
"p = {\"name\":\"Alex\", \"x\":\"!!\"}\n",
"Hello(**p)\n",
"[1,]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.4.3 Desempaquetado"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 1 2\n",
"0 4 5\n",
"[6, 7, 8] 1 2\n",
"6 7 8\n",
"{'a': 9, 'b': 10, 'c': 11} 1 2\n",
"9 10 11\n"
]
}
],
"source": [
"def unpack(a,b=1,c=2):\n",
" print(a,b,c)\n",
"\n",
"l = [6,7,8] \n",
"d = {\"a\":9,\"b\":10,\"c\":11} \n",
"unpack(0)\n",
"unpack(0, 4, 5)\n",
"unpack(l)\n",
"unpack(*l)\n",
"unpack(d)\n",
"unpack(**d)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.5 Ejercicios\n",
"### 1.5.1 Imprimir todos los numeros pares entre 0 y 20 usando *for* o *while*."
]
},
{
......@@ -550,12 +785,12 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4.2 Inprimir todos los numeros myores a 10 de la lista A"
"### 1.5.2 Imprimir todos los numeros mayores a 10 de la lista A"
]
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
......@@ -567,31 +802,106 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4.3 Dadas dos listas A y B, obten una lista con los elementos comunes a las dos listas (A∩B)."
"### 1.5.3 Dadas dos listas A y B, obten una lista con sus elementos comunes (A∩B)."
]
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n",
"b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.4 Pregunta al usario cuantos numeros de la secuancia Fibonacci quiere calcular y escribe una funcion que calcule la secuencia e imprima el resultado."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"def fibonacci(n):\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.5 Escribe una funcion que sume todos los numeros en una lista usando for."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"a = [8, 2, 3, 0, 7]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.6 Escribe una funcion que tome una lista y regrese los elementos unicos en la lista.\n"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"a = [1,2,2,3,3,3,3,4,5,5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.7 Escribe una funcion que indique si un numero es o no perfecto.\n",
"[Wikipedia:](https://es.wikipedia.org/wiki/N%C3%BAmero_perfecto) *Un número perfecto es un número natural que es igual a la suma de sus divisores propios positivos. Dicho de otra forma, un número perfecto es aquel que es amigo de sí mismo.\n",
"Así, 6 es un número perfecto porque sus divisores propios son 1, 2 y 3; y 6 = 1 + 2 + 3. Los siguientes números perfectos son 28, 496 y 8128.*\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'raw_input' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-8-504d5d148c52>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnum\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mraw_input\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Choose a number: \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mNameError\u001b[0m: name 'raw_input' is not defined"
"name": "stdout",
"output_type": "stream",
"text": [
"Escribe un nuemero:8\n"
]
}
],
"source": [
"num = int(raw_input(\"Choose a number: \"))\n",
"\n",
"\n",
"\n"
"def perfect(x):\n",
" pass\n",
"numero = input(\"Escribe un nuemero:\")\n",
"perfect(numero)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.8 Escribe una funcion que imprima las prieras *n* filas del triangulo de Pascal.\n",
"[Wolfram](http://mathworld.wolfram.com/PascalsTriangle.html):\n",
"El triángulo de Pascal es un triángulo numérico con números dispuestos en filas escalonadas de manera tal que:\n",
"$a_{nr}=\\frac{n!}{r!(n-r)!}=\\binom{n}{r}$\n"
]
},
{
......@@ -600,8 +910,42 @@
"metadata": {},
"outputs": [],
"source": [
"x = input('What is your name?: ')\n",
"\n"
"def pascal(n):\n",
" pass\n",
"numero = input(\"Indica el numero de filas:\")\n",
"pascal(numero)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.9 Escribe una funcion que indique si una frase es un panagrama.\n",
"[Wikipedia](https://es.wikipedia.org/wiki/Pangrama):Un pangrama (del griego: παν γραμμα, «todas las letras») o frase holoalfabética es un texto que usa todas las letras posibles del alfabeto de un idioma. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.5.10 Escribe un programa que imprima el siguiente un **for** anidado.\n",
"1\n",
"\n",
"22\n",
"\n",
"333\n",
"\n",
"4444\n",
"\n",
"55555\n",
"\n",
"666666\n",
"\n",
"7777777\n",
"\n",
"88888888\n",
"\n",
"999999999"
]
},
{
......
......@@ -241,7 +241,7 @@
},
{
"cell_type": "code",
"execution_count": 55,
"execution_count": 2,
"metadata": {},
"outputs": [
{
......@@ -297,6 +297,38 @@
"print(list(doublesG))"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Cuatos Fibonacci?: 6\n",
"0\n",
"1\n",
"1\n",
"2\n",
"3\n",
"5\n"
]
}
],
"source": [
"a = int(input('Cuatos Fibonacci?: '))\n",
"\n",
"def fib(n):\n",
" a, b = 0, 1\n",
" for _ in range(n):\n",
" yield a\n",
" a, b = b, a + b\n",
"\n",
"for n in fib(a):\n",
" print(n)"
]
},
{
"cell_type": "markdown",
"metadata": {},
......
......@@ -12,31 +12,31 @@
},
{
"cell_type": "code",
"execution_count": 28,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" tricks = [] # Variable de clase\n",
" kind = 'canine' # Variable de clase\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" tricks = [] # Variable de clase\n",
" kind = 'Canis Lopus' # Variable de clase\n",
" def __init__(self, name): # Constructor de clase\n",
" self.name = name # Variable de instancia\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 29,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
......@@ -47,7 +47,7 @@
},
{
"cell_type": "code",
"execution_count": 30,
"execution_count": 7,
"metadata": {},
"outputs": [
{
......@@ -57,7 +57,7 @@
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-30-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-7-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute 'name'"
]
}
......@@ -68,7 +68,7 @@
},
{
"cell_type": "code",
"execution_count": 31,
"execution_count": 8,
"metadata": {},
"outputs": [
{
......@@ -77,7 +77,7 @@
"'Max'"
]
},
"execution_count": 31,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
......@@ -88,7 +88,7 @@
},
{
"cell_type": "code",
"execution_count": 33,
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
......@@ -98,16 +98,16 @@
},
{
"cell_type": "code",
"execution_count": 34,
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 34,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
......@@ -118,16 +118,16 @@
},
{
"cell_type": "code",
"execution_count": 36,
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'canine'"
"'Canis Lopus'"
]
},
"execution_count": 36,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
......@@ -139,45 +139,404 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['roll over', 'play dead']"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Max.add_trick('roll over')\n",
"Max.add_trick('play dead')\n",
"Keeper.tricks\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"Max. def add_trick(self, trick):\n",
" self.tricks.append(trick)"
"class Dog:\n",
" __kind = 'Canis Lopus' # Variable de clase Privada\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" def get_kind(self):\n",
" return self.__kind"
]
},
{
"cell_type": "markdown",
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "type object 'Dog' has no attribute '__kind'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-14-4cb7b0dc9a4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__kind\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute '__kind'"
]
}
],
"source": [
"Dog.__kind"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lopus'"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"## 3.2 Herencia"
"Max = Dog(\"Max\")\n",
"Max.get_kind()\n",
"Max._Dog__kind"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.3 Polimorfismo"
"Notas:\n",
"* **Self** no es una palabra reservada en Python solo una convencion.\n",
"* [\"why explicit self has to stay\", por Guido van Rossum](http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html)\n",
"* [We are all consenting adults](https://python-guide-chinese.readthedocs.io/zh_CN/latest/writing/style.html#we-are-all-consenting-adults) Python permite muchos trucos, y algunos de ellos son potencialmente peligrosos. Un buen ejemplo es que cualquier código de cliente puede anular las propiedades y los métodos de un objeto: no hay una palabra clave \"privada\" en Python. Esta filosofía, muy diferente de los lenguajes altamente defensivos como Java, que ofrecen muchos mecanismos para evitar cualquier uso indebido, se expresa con el dicho: \"Todos somos adultos\".\n",
"\n",
"## 3.3 Decoradores \n",
"Los decoradores son una conveniencia sintáctica, que permite que un archivo fuente de Python diga qué va a hacer con el resultado de una función o una declaración de clase antes de la declaración.\n",
"\n",
"### 3.3.1 Metodos Estaticos\n",
"**@staticmethod**\n",
"Los metodos estaticos no requieren que exista una instancia de la clase y no conocen nada sobre la clase solo sus parametros de entrada.\n",
"\n",
"\n",
"### 3.3.2 Metodos de Clase\n",
"**@classmethod** Los metodos de clase no requiren que exista a una instancia de la clase y tiene acceso a las variables de clase y solo toman como entrada un unico parametro.\n",
"\n",
"### 3.3.3 Set y Get no so Pythonicos\n",
"**@property** y **@*PROPIEDAD*.setter**, permiten acceder y modificar miembros de foma Pythonica.\n",
"\n",
"### 3.3.2 Destructor\n",
"En Python, los destructores no son tan necesarios como en C ++ porque Python tiene un recolector de basura que maneja la administración de la memoria automáticamente.\n",
"El método **__del __ ()** es el método conocido como destructor en Python. Se llama cuando todas las referencias al objeto se han eliminado, es decir, cuando un objeto se recolecta como basura."
]
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"class Dog:\n",
" __kind = 'Canis Lopus' # Variable privada de clase, para evitar que se modifique\n",
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia, para tenenr trucos diferentes por instancia\n",
" self.__age = 0\n",
" @property\n",
" def age(self):\n",
" return self.__age\n",
" @age.setter\n",
" def age(self, age):\n",
" self.__age = age\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" @classmethod\n",
" def get_kind(cls):\n",
" return cls.__kind\n",
" @staticmethod\n",
" def bark(times):\n",
" print(\"Guau \"*times)\n",
" def __str__(self):\n",
" return self.name + \" es un \" + self.__kind\n",
" def __del__(self): \n",
" print(self.name + \" a muerto\") "
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'dict_items' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-12-afcb87a7ff57>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mhelp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdict_items\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'dict_items' is not defined"
"name": "stdout",
"output_type": "stream",
"text": [
"Guau Guau Guau \n"
]
}
],
"source": [
"Dog.bark(3)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Canis Lopus'"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Dog.get_kind()"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.age+=1\n",
"print(Max.age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.4 Herencia"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog):\n",
" origin = \"Bélgica\"\n",
" def fetch(self):\n",
" print(\"Fetch\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Max = Malinois(\"Max\")\n",
"print(max.get_kind())\n",
"print(max.name)\n",
"print(max.tricks)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Malinois(Dog):\n",
" __breed = \"Malinois\"\n",
" origin = \"Bélgica\"\n",
" def __init__(self, name):\n",
" super().__init__(name) #Dog.__int__(self,name)\n",
" self.tricks = [\"Fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
" def __str__(self): #Overriding\n",
" # Obteniendo variable privada de la clase Padre\n",
" return self.name + \" es un \" + self._Dog__kind + \" de raza \" + self.__breed"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"keeper = Malinois(\"Keeper\")\n",
"print(keeper.get_kind())\n",
"print(keeper.name)\n",
"print(keeper.tricks)\n",
"print(keeper)\n",
"del(keeper)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Police:\n",
" uniform = \"Azul\"\n",
" def __init__(self, section):\n",
" self.section=section\n",
" def get_section(self):\n",
" return self.section\n",
" def __del__(self): \n",
" print(\"Dia de Jubilacion\") \n",
" \n",
"# Herencia Multiple\n",
"class Malinois(Dog, Police):\n",
" __breed = \"Malinois\"\n",
" origin = \"Bélgica\"\n",
" def __init__(self, name):\n",
" #Dog.__init__(self, name) # No usar en herencia multiple\n",
" #super(__Dog__,self).__init__(name)\n",
" #Police.__init__(self,\"K9\")\n",
" #super(__Police__,self).__init__(\"K9\")\n",
" self.tricks = [\"fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
" def __str__(self): #Overriding\n",
" # Obteniendo variable privada de la clasfridae Padre\n",
" return self.name + \" es un \" + self._Dog__kind + \" Policia de raza \" + self.__breed + \" con uniforme \" + self.uniform\n",
"# def __del__(self): #Overriding\n",
"# return \"Llego el Fin\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"frida = Malinois(\"Frida\")\n",
"print(frida.__dict__)\n",
"\n",
"print(frida.get_section())\n",
"print(frida)\n",
"del(frida)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"## 3.5 Polimorfismo\n",
"Polimorfismo se refiere a la caracteristica de que la misma clase de objeto pueda adquirir varias formas. A diferencia de otros lenguajes como C++ en donde para lograr polimorfismo se requiren de considereciones especiales en la herencia y la sintaxis. En Python el polimorfismo es consecuencia de el tipado dinamico sin tener que tener considerecciones especiales."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.6 Ejercicios\n",
"Como recordarán, el proyecto final consiste en desarrollar un periódico inteligente en el cual, un usuario podrá elegir ciertos temas de interés personal, por ejemplo: ”Política de relaciones exteriores”, ”Francia”, ”Música”, ”Pearl Jam”; y el sistema colectará noticias de diversas fuentes y deberá procesar los documentos para determinar la relevancia de los mismos con respecto a los temas de interés del usuario.\n",
"\n",
"**Instrucciones**: Lea con atención las siguientes especificaciones y diseñe las clases descritas a continuación.\n",
"Diseñe en pyhton las clases siguientes de manera que contengan los atributos y comportamientos necesarios para ser incluidas como parte del proyecto \"periódico inteligente\". No es necesario que implemente los métodos de las clases pero sí es necesario que los declare aunque estén vacios, es decir, el esqueleto de las clases. Considere el uso de los siguientes conceptos:\n",
"\n",
"* constructor\n",
"* variables de instancia\n",
"* variable de clase\n",
"* métodos de instancia\n",
"* métodos de clase\n",
"* herencia\n",
"* polimorfismo\n",
"\n",
"Además de estas clases, puede incluir algunas otras clases que considere necesario incluyendo la justificación. \n",
"\n",
"### 3.6.1 La Clase Nota\n",
"La clase Nota debe abstraer el concepto de una nota periodística; una noticia que aparece en alguna fuente informativa. Algunas características principales de las Notas es que debe pertenecer a alguna categoría como \"deportes\" o \"cultura\", deben tener un título, un autor, una fecha de publicación, entre otros atributos.\n",
"### 3.6.2 La Clase Fuente\n",
"La clase Fuente debe abstraer el concepto de una fuente informativa como por ejemplo \"La Jornada\" o \"noticias MVS\". Una característica principal de las Fuentes es que generan Notas (ver ejercicio 1). \n",
"### 3.6.3 La Clase Editor\n",
"La clase Editor debe abstraer el concepto de una persona (o robot) que se encarga de recopilar las Notas de diversas Fuentes para un determinado tema (sección). Por ejemplo un Editor de la sección \"cultura\" debe ser capaz de identificar las notas que corresponden a este tema. También debe ser capaz de consultar las Fuentes y autores que proporcionan las mejores Notas para la sección que le corresponde, es decir, es experto en uno de los temas. \n",
"### 3.6.4 La Clase Editorial\n",
"La clase Editorial debe abstraer el concepto del consejo editorial de un periódico. Es una clase muy importante para el proyecto ya que la Editorial decide cuáles notas deben aparecer en el día y determina el grado de relevancia de las notas del día para cada sección.Para ello, debe interactuar con los Reporteros para decidir las notas que deben incluirse, considerando los temas de interés y las valoraciones de los Reporteros."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
......
......@@ -12,7 +12,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
......@@ -27,7 +27,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 6,
"metadata": {},
"outputs": [
{
......@@ -36,7 +36,7 @@
"'Canis Lopus'"
]
},
"execution_count": 4,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
......@@ -47,7 +47,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 7,
"metadata": {},
"outputs": [
{
......@@ -57,7 +57,7 @@
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-7-629675d46941>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute 'name'"
]
}
......@@ -68,7 +68,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 8,
"metadata": {},
"outputs": [
{
......@@ -77,7 +77,7 @@
"'Max'"
]
},
"execution_count": 6,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
......@@ -88,7 +88,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
......@@ -98,7 +98,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 10,
"metadata": {},
"outputs": [
{
......@@ -107,7 +107,7 @@
"'Canis Lopus'"
]
},
"execution_count": 8,
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
......@@ -118,7 +118,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 11,
"metadata": {},
"outputs": [
{
......@@ -127,7 +127,7 @@
"'Canis Lopus'"
]
},
"execution_count": 9,
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
......@@ -139,7 +139,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 12,
"metadata": {},
"outputs": [
{
......@@ -148,7 +148,7 @@
"['roll over', 'play dead']"
]
},
"execution_count": 10,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
......@@ -161,7 +161,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
......@@ -178,7 +178,7 @@
},
{
"cell_type": "code",
"execution_count": 30,
"execution_count": 14,
"metadata": {},
"outputs": [
{
......@@ -188,7 +188,7 @@
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-30-4cb7b0dc9a4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__kind\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-14-4cb7b0dc9a4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mDog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__kind\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: type object 'Dog' has no attribute '__kind'"
]
}
......@@ -239,6 +239,9 @@
"### 3.3.2 Metodos de Clase\n",
"**@classmethod** Los metodos de clase no requiren que exista a una instancia de la clase y tiene acceso a las variables de clase y solo toman como entrada un unico parametro.\n",
"\n",
"### 3.3.3 Set y Get no so Pythonicos\n",
"**@property** y **@*PROPIEDAD*.setter**, permiten acceder y modificar miembros de foma Pythonica.\n",
"\n",
"### 3.3.2 Destructor\n",
"En Python, los destructores no son tan necesarios como en C ++ porque Python tiene un recolector de basura que maneja la administración de la memoria automáticamente.\n",
"El método **__del __ ()** es el método conocido como destructor en Python. Se llama cuando todas las referencias al objeto se han eliminado, es decir, cuando un objeto se recolecta como basura."
......@@ -246,7 +249,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
......@@ -255,6 +258,13 @@
" def __init__(self, name):\n",
" self.name = name # Variable de instancia\n",
" self.tricks = [] # Variable de instancia, para tenenr trucos diferentes por instancia\n",
" self.__age = 0\n",
" @property\n",
" def age(self):\n",
" return self.__age\n",
" @age.setter\n",
" def age(self, age):\n",
" self.__age = age\n",
" def add_trick(self, trick):\n",
" self.tricks.append(trick)\n",
" @classmethod\n",
......@@ -271,7 +281,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 17,
"metadata": {},
"outputs": [
{
......@@ -289,7 +299,7 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 18,
"metadata": {},
"outputs": [
{
......@@ -298,7 +308,7 @@
"'Canis Lopus'"
]
},
"execution_count": 14,
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
......@@ -307,6 +317,25 @@
"Dog.get_kind()"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"Max = Dog(\"Max\")\n",
"Max.age+=1\n",
"print(Max.age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -316,7 +345,7 @@
},
{
"cell_type": "code",
"execution_count": 21,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -328,21 +357,11 @@
},
{
"cell_type": "code",
"execution_count": 22,
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lopus\n",
"Max\n",
"[]\n"
]
}
],
"outputs": [],
"source": [
"max = Malinois(\"Max\")\n",
"Max = Malinois(\"Max\")\n",
"print(max.get_kind())\n",
"print(max.name)\n",
"print(max.tricks)"
......@@ -350,7 +369,7 @@
},
{
"cell_type": "code",
"execution_count": 26,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -369,21 +388,9 @@
},
{
"cell_type": "code",
"execution_count": 61,
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Canis Lopus\n",
"Keeper\n",
"['fetch']\n",
"Keeper es un Canis Lopus Policia de raza Malinois con uniforme Azul\n",
"Keeper a muerto\n"
]
}
],
"outputs": [],
"source": [
"keeper = Malinois(\"Keeper\")\n",
"print(keeper.get_kind())\n",
......@@ -395,7 +402,7 @@
},
{
"cell_type": "code",
"execution_count": 84,
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
......@@ -413,30 +420,32 @@
" __breed = \"Malinois\"\n",
" origin = \"Bélgica\"\n",
" def __init__(self, name):\n",
" Dog.__init__(self, name)\n",
" Police.__init__(self,\"K9\")\n",
" #super(__Police__,self).__init__(\"K9\")\n",
" Dog.__init__(self, name) # No usar en herencia multiple\n",
" #super(__Dog__,self).__init__(name)\n",
" self.tricks = [\"fetch\"] # Variable de instancia\n",
" def fetch(self):\n",
" print(\"fetch\")\n",
" def __str__(self): #Overriding\n",
" # Obteniendo variable privada de la clase Padre\n",
" # Obteniendo variable privada de la clasfridae Padre\n",
" return self.name + \" es un \" + self._Dog__kind + \" Policia de raza \" + self.__breed + \" con uniforme \" + self.uniform\n",
" def __str__(self): #Overriding\n",
" return \"Llego el Fin\"\n"
"# def __del__(self): #Overriding\n",
"# return \"Llego el Fin\"\n"
]
},
{
"cell_type": "code",
"execution_count": 85,
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name': 'Frida', 'tricks': ['fetch'], 'section': 'K9'}\n",
"{'_Dog__age': 0, 'name': 'Frida', 'section': 'K9', 'tricks': ['fetch']}\n",
"K9\n",
"Llego el Fin\n",
"Frida es un Canis Lopus Policia de raza Malinois con uniforme Azul\n",
"Frida a muerto\n"
]
}
......@@ -452,33 +461,19 @@
},
{
"cell_type": "code",
"execution_count": 80,
"execution_count": null,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'Mailinois' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-80-35e40b7a7cfb>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mMailinois\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__dict__\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'Mailinois' is not defined"
]
}
],
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"\n",
"\n",
"## 3.5 Polimorfismo\n",
"Polimorfismo se refiere a la caracteristica de que la misma clase de objeto pueda adquirir varias formas. A diferencia de otros lenguajes como C++ en donde para lograr polimorfismo se requiren de considereciones especiales en la herencia y la sintaxis. En Python el polimorfismo es consecuencia de el tipado dinamico sin tener que tener considerecciones especiales."
"Polimorfismo se refiere a la caracteristica de que la misma clase de objeto pueda adquirir varias formas. A diferencia de otros lenguajes como C++ en donde para lograr polimorfismo se requiren de considereciones especiales en la herencia y la sintaxis, en Python el polimorfismo es consecuencia de el tipado dinamico sin tener que tener considerecciones especiales."
]
},
{
......@@ -548,6 +543,13 @@
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
......
No preview for this file type
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment