{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyPBsJewkIUvtdqg2D++Dsnv", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "# Métodos mágicos\n", "1. Los *métodos mágicos* son **métodos especiales** que se definen en una clase y tienen un nombre que comienza y termina con doble guion bajo.\n", "2. En inglés, se les conoce como “dunders” (de “double underscores”). Estos métodos permiten definir comportamientos especiales para los objetos de la clase que no pueden ser representados en un método regular." ], "metadata": { "id": "GRQl9Ik6iBLe" } }, { "cell_type": "code", "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GEEpCS05fIPK", "outputId": "69777222-0d82-4f25-f679-110b4c7b73db" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[1, 2, 3]\n", "3\n", "1\n", "4\n", "[4, 2, 3, 4, 5, 6]\n" ] } ], "source": [ "class MiLista:\n", " def __init__(self, *args):\n", " self.lista = list(args)\n", "\n", " def __str__(self):\n", " return str(self.lista)\n", "\n", " def __len__(self):\n", " return len(self.lista)\n", "\n", " def __getitem__(self, key):\n", " return self.lista[key]\n", "\n", " def __setitem__(self, key, value):\n", " self.lista[key] = value\n", "\n", " def __add__(self, other):\n", " nueva_lista = self.lista.copy()\n", " nueva_lista.extend(other.lista)\n", " return MiLista(*nueva_lista)\n", "\n", "lista1 = MiLista(1, 2, 3)\n", "lista2 = MiLista(4, 5, 6)\n", "\n", "print(lista1) # [1, 2, 3]\n", "print(len(lista1)) # 3\n", "print(lista1[0]) # 1\n", "lista1[0] = 4\n", "print(lista1[0]) # 4\n", "print(lista1 + lista2) # [4, 2, 3, 4, 5, 6]" ] } ] }