{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "35c14ca3", "metadata": { "id": "35c14ca3" }, "source": [ "# Ejemplo constructor, atributos, métodos" ] }, { "cell_type": "markdown", "source": [ "## Fracción" ], "metadata": { "id": "BVx5ub9nqNSU" }, "id": "BVx5ub9nqNSU" }, { "cell_type": "code", "source": [ "class Fraccion:\n", "\n", " def __init__(self, num=0, den=1): # método constructor. Los parámetros tienen valor por defecto\n", " self.num = num\n", " self.den = den\n", "\n", " def multiplica(self, b):\n", " num = self.num * b.num\n", " den = self.den * b.den\n", " r = Fraccion(num, den)\n", " return r\n", "\n", " def imprime(self):\n", " print(self.num, \"/\", self.den)\n", "\n", "def main():\n", " a = Fraccion(4, 5)\n", " print('\\na:')\n", " a.imprime()\n", "\n", " b = Fraccion(2, 3)\n", " print('\\nb:')\n", " b.imprime()\n", "\n", " c = a.multiplica(b) # c es el resultado de multiplicar a por b\n", " print('\\nc:')\n", " c.imprime()\n", "\n", " z = Fraccion() # si no ponemos argumentos se toman los valores por defecto del constructor\n", " print('\\nz:')\n", " z.imprime()\n", "\n", "if __name__==\"__main__\":\n", " main()" ], "metadata": { "id": "zAFOMoXSqSp-", "outputId": "0cfe2897-73a3-4be1-9139-09000a7246ad", "colab": { "base_uri": "https://localhost:8080/" } }, "id": "zAFOMoXSqSp-", "execution_count": 1, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "a:\n", "4 / 5\n", "\n", "b:\n", "2 / 3\n", "\n", "c:\n", "8 / 15\n", "\n", "z:\n", "0 / 1\n" ] } ] }, { "cell_type": "markdown", "id": "74e15ae2", "metadata": { "id": "74e15ae2" }, "source": [ "## Galletas" ] }, { "cell_type": "code", "execution_count": 2, "id": "94f00d48", "metadata": { "id": "94f00d48", "outputId": "be520602-0113-42ed-8864-f440e45f0056", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Se acaba de crear una galleta cuadrada y dulce.\n", "Se acaba de crear una galleta redonda y salada.\n" ] } ], "source": [ "class Galleta:\n", " chocolate = False\n", "\n", " def __init__(self, forma, sabor):\n", " self.forma = forma\n", " self.sabor = sabor\n", " print(f\"Se acaba de crear una galleta {self.forma} y {self.sabor}.\")\n", "\n", " def chocolatear(self):\n", " self.chocolatear = True\n", "\n", " def tiene_chocolate(self):\n", " if self.chocolate:\n", " print(\"Soy una galleta chocolateada\")\n", " else:\n", " print(\"Soy una galleta sin chocolate\")\n", "\n", "g1 = Galleta(\"cuadrada\", \"dulce\")\n", "g2 = Galleta(\"redonda\", \"salada\")" ] }, { "cell_type": "code", "execution_count": 3, "id": "6c5bc91c", "metadata": { "id": "6c5bc91c" }, "outputs": [], "source": [ "#g3 = Galleta() # ERROR, ya que no hemos proporcionado los atributos" ] }, { "cell_type": "markdown", "id": "5481270c", "metadata": { "id": "5481270c" }, "source": [ "Para evitar el error podemos establecer unos atributos por defecto en el constructor." ] }, { "cell_type": "code", "execution_count": 4, "id": "9e49a70e", "metadata": { "id": "9e49a70e", "outputId": "4a064b70-3e33-41b3-b6dc-02150698028e", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Se acaba de crear una galleta cuadrada y dulce.\n", "Se acaba de crear una galleta redonda y salada.\n", "Se acaba de crear una galleta None y None.\n" ] } ], "source": [ "class Galleta:\n", " chocolate = False\n", "\n", " def __init__(self, forma = None, sabor = None): # añadimos atributos por defecto\n", " self.forma = forma\n", " self.sabor = sabor\n", " print(f\"Se acaba de crear una galleta {self.forma} y {self.sabor}.\")\n", "\n", " def chocolatear(self):\n", " self.chocolatear = True\n", "\n", " def tiene_chocolate(self):\n", " if self.chocolate:\n", " print(\"Soy una galleta chocolateada\")\n", " else:\n", " print(\"Soy una galleta sin chocolate\")\n", "\n", "g1 = Galleta(\"cuadrada\", \"dulce\")\n", "g2 = Galleta(\"redonda\", \"salada\")\n", "g3 = Galleta() # ahora no da error, aunque la frase no es buena" ] }, { "cell_type": "code", "execution_count": 5, "id": "5a5040f0", "metadata": { "id": "5a5040f0", "outputId": "c6a40bdd-3771-4043-ae53-729b30526304", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Se acaba de crear una galleta cuadrada y dulce.\n", "Se acaba de crear una galleta redonda y salada.\n" ] } ], "source": [ "class Galleta:\n", " chocolate = False\n", "\n", " def __init__(self, forma = None, sabor = None):\n", " self.forma = forma\n", " self.sabor = sabor\n", " if forma is not None and sabor is not None:\n", " print(f\"Se acaba de crear una galleta {self.forma} y {self.sabor}.\")\n", "\n", " def chocolatear(self):\n", " self.chocolatear = True\n", "\n", " def tiene_chocolate(self):\n", " if self.chocolate:\n", " print(\"Soy una galleta chocolateada\")\n", " else:\n", " print(\"Soy una galleta sin chocolate\")\n", "\n", "g1 = Galleta(\"cuadrada\", \"dulce\")\n", "g2 = Galleta(\"redonda\", \"salada\")\n", "g3 = Galleta() # ahora se crea sin error y sin frase" ] }, { "cell_type": "markdown", "source": [ "## Planetas" ], "metadata": { "id": "NFaJbObMqxXI" }, "id": "NFaJbObMqxXI" }, { "cell_type": "code", "source": [ "class Planeta:\n", " def __init__(self, nombre, radio, gravedad):\n", " self.nombre = nombre\n", " self.radio = radio # en Km\n", " self.gravedad = gravedad # m/seg^2\n", " self.sistema = \"Solar\" # todos los planetas de esta clase pertenecen al sistema Solar\n", "\n", " def orbita(self):\n", " return f'{self.name} orbita en el sistema {self.sistema}'\n", "\n", "tierra = Planeta('Tierra', 6371, 9.8)\n", "mercurio = Planeta('Mercurio', 2440, 3.7)\n", "jupiter = Planeta('Júpiter', 69911, 24.8)\n", "\n", "print(f\"El radio de la {tierra.nombre} es de {tierra.radio} Km, una gravedad de {tierra.gravedad} y pertenece al sistema {tierra.sistema}.\")" ], "metadata": { "id": "ypkUu4Trq0WV", "outputId": "09d725ec-0142-4783-8f35-e3eaec77fb0a", "colab": { "base_uri": "https://localhost:8080/" } }, "id": "ypkUu4Trq0WV", "execution_count": 6, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "El radio de la Tierra es de 6371 Km, una gravedad de 9.8 y pertenece al sistema Solar.\n" ] } ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" }, "colab": { "name": "calisto2_0050.ipynb", "provenance": [], "include_colab_link": true } }, "nbformat": 4, "nbformat_minor": 5 }