{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyO/2H4X619OEgf2PthlvaHD",
"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": [
""
]
},
{
"cell_type": "markdown",
"source": [
"# Enum\n",
"¿Cómo crear un enum en Python?\n",
"Necesitamos importar la clase `enum` y dentro de ella el método `Enum` ya que no existen enums de forma nativa en Python."
],
"metadata": {
"id": "SWVbogKycH50"
}
},
{
"cell_type": "code",
"source": [
"from enum import Enum\n",
"\n",
"class Season(Enum):\n",
" SPRING = 1\n",
" SUMMER = 2\n",
" AUTUMN = 3\n",
" WINTER = 4\n",
"\n",
"# printing enum member as string\n",
"print(Season.SPRING)\n",
"\n",
"# printing name of enum member using \"name\" keyword\n",
"print(Season.SPRING.name)\n",
"\n",
"# printing value of enum member using \"value\" keyword\n",
"print(Season.SPRING.value)\n",
"\n",
"# printing the type of enum member using type()\n",
"print(type(Season.SPRING))\n",
"\n",
"# printing enum member as repr\n",
"print(repr(Season.SPRING))\n",
"\n",
"# printing all enum member using \"list\" keyword\n",
"print(list(Season))\n",
"\n",
"# recorriendo todos los valores del enum\n",
"for val in Season:\n",
" print()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "MKw0U7K1coQS",
"outputId": "4249740d-1ce8-479f-9aa0-2ac0a19b8597"
},
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Season.SPRING\n",
"SPRING\n",
"1\n",
"\n",
"\n",
"[, , , ]\n",
"\n",
"\n",
"\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"from enum import Enum\n",
"\n",
"class Color(Enum):\n",
" ROJO = 1\n",
" VERDE = 2\n",
" AZUL = 3\n",
"\n",
"# Accediendo a los valores del enum\n",
"print(Color.ROJO) # Color.ROJO\n",
"print(Color.VERDE) # Color.VERDE\n",
"print(Color.AZUL) # Color.AZUL\n",
"\n",
"# Comparando valores del enum\n",
"print(Color.ROJO == Color.VERDE) # False\n",
"print(Color.ROJO == Color.ROJO) # True\n",
"\n",
"# Accediendo al valor entero del enum\n",
"print(Color.ROJO.value) # 1\n",
"print(Color.VERDE.value) # 2\n",
"print(Color.AZUL.value) # 3"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "E2352h3WeV3X",
"outputId": "0462f372-85d0-4e50-ea0c-6f5097cb0b53"
},
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Color.ROJO\n",
"Color.VERDE\n",
"Color.AZUL\n",
"False\n",
"True\n",
"1\n",
"2\n",
"3\n"
]
}
]
}
]
}