Hopp til innhold

Enumerations

Skip to content

This doth be a machine-wrought text which may contain errors!

Enums

Enums (enumerations) ‘tis a manner to define a sort of datum which may hold but a limited set of preordained values. This maketh it easier to shun errors, for a variable then may possess naught save valid worths.

‘Gainst all odds, Enums serve not strictly unto validation, yet they aid us in bounding which values are lawful for a variable, and so they may help prevent mishaps.

By way of example, if thou hast a class that doth represent a chariot, thou mightest use an Enum to decree which hues the said vehicle may don:

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

Wherfore?

Our IDE granteth better autocomplete when we employ enums, and we shun (make it hard to do the deed of) setting invalid values. If we attempt to assign a colour not defined within CarColor, shall Python cast forth an error. This maketh the code more sturdy and easier to maintain. The fewer errors that may arise, the finer quality our code possesseth.

Imagine ye have a function which handleth payment methods: PayPal, VISA, MASTERCARD, and BITCOIN. By using an Enum for such means, we ensure this function receiveth naught but valid payment methods, nor shall it accept "MASTERCARDD" or "CASH", which might bring about faults in the programme.

Enum Meme

Easy Task I - Forge an Enum

Forge thou an Enum named EyeColor, and implant it within the Person class of yon prior module. The EyeColor shall bear these values:

  • BLUE
  • BROWN
  • GREEN
  • HAZEL

The Enumeration is oft used in the crafting of games

Shouldst thou peruse the writs of sundry pastimes, thou shalt espie that they employ Enum’s to ordain such things as arms, foes, levels and the like. ‘Tis because it maketh easier to handle these matters within the code, and thereby rendereth more plain to shun errors.

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

Hark! Thou hast attained understanding of enumerations