Hopp til innhold

Rodeo Ranks,

Skip to content

This here’s a machine-translated text that might contain some errors!

Enums

Enums (enumerations) is a way to define a data type that can only hold a limited set of pre-defined values. This makes it easier to avoid mistakes by ensuring a variable can only have valid values.

Strictly speakin’, enums ain’t used for validation, but they help us limit which values are valid for a variable, thereby helpin’ prevent errors.

For instance, if you got yourself a class representin’ a car, you could use an Enum to define what colors the ride’s allowed to wear:

from enum import Enum

class CarColor(Enum):
    RED = "red"
    BLUE = "blue"
    GREEN = "green"
    BLACK = "black"
    WHITE = "white"

class Car:
    def __init__(self, make: str, model: str, year: int, color: CarColor):
        self.make = make
        self.model = model
        self.year = year
        self.color = color

Why?

Our IDE gives better autocomplete when we use enums, and it makes it tough to set invalid values. If you try to assign a color that ain’t defined in CarColor, Python’ll throw an error. This keeps the code sturdy and easier to maintain. The fewer mistakes that can happen, the higher quality our code ends up bein’.

Picture us havin’ a function that handles payment methods: PayPal, VISA, MASTERCARD, and BITCOIN. By usin’ an Enum for payment methods, we can make sure the function only takes valid options, not stuff like "MASTERCARDD" or "CASH", which could cause trouble in the program.

Enum Meme

Easy Task 1 - Make an Enum

Make an Enum called EyeColor and put it to work in the Person class from last time around. That EyeColor needs these values on its belt:

  • BLUE
  • BROWN
  • GREEN
  • HAZEL

Enums are used quite a bit in game development

If you look through the docs on various games, you’ll often see ‘em usin’ Enums to define things like weapons, enemies, levels, and such. That’s because it makes dealin’ with that kind of stuff in the code easier, and helps keep mistakes from happenin’.

https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/blockpistonstate?view=minecraft-bedrock-stable

Well done partner y'all got a handle on them enums now