Home > Software design >  Python 3 - How do I use a loop to create multiple classes at once?
Python 3 - How do I use a loop to create multiple classes at once?

Time:05-21

I'm trying to make a D&D character creator, although I need to make an individual instance of a class for every single 'class' and 'race' in this.

I've made it so that every instance is created on a seperate line, one after another (so it's about 45 lines including comments right now), however, I was wondering if I could make a loop to create all of the instances in just a few lines of code.

I've looked at other responses although none of them quite worked in doing what I wanted it to do, so I was hoping someone could help me out here.

The code right now looks like this:

## Classes ##

 #creates barbarian as a class
Barbarian = DnD_Class("Barbarian")
 #creates bard as a class
Bard = DnD_Class("Bard")
 #creates cleric as a class
Cleric = DnD_Class("Cleric")
 #creates druid as a class
Druid = DnD_Class("Druid")
 #creates fighter as a class
Fighter = DnD_Class("Fighter")
 #creates monk as a class
Monk = DnD_Class("Monk")
 #creates paladin as a class
Paladin = DnD_Class("Paladin")
 #creates ranger as a class
Ranger = DnD_Class("Ranger")
 #creates rogue as a class
Rogue = DnD_Class("Rogue")
 #creates sorcerer as a class
Sorcerer = DnD_Class("Sorcerer")
 #creates warlock as a class
Warlock = DnD_Class("Warlock")
 #creates wizard as a class
Wizard = DnD_Class("Wizard")

## Races ##

 #creates dragonborn as a race
Dragonborn = DnD_Race("Dragonborn")
 #creates dwarf as a race
Dwarf = DnD_Race("Dwarf")
 #creates elf as a race
Elf = DnD_Race("Elf")
 #creates gnome as a race
Gnome = DnD_Race("Gnome")
 #creates half-elf as a race
Half_Elf = DnD_Race("Half-Elf")
 #creates halfling as a race
Halfling = DnD_Race("Halfling")
 #creates half-orc as a race
Half_Orc = DnD_Race("Half-Orc")
 #creates human as a race
Human = DnD_Race("Human")
 #creates tiefling as a race
Tiefling = DnD_Race("Tiefling")

CodePudding user response:

I'd suggest collecting your classes in a dictionary keyed on the class name, rather than having named variables for each:

dnd_classes = {
    class_name: DnD_Class(class_name)
    for class_name in (
        "Barbarian",
        "Bard",
        "Cleric",
        "Druid",
        "Fighter",
        "Monk",
        "Paladin",
        "Ranger",
        "Rogue",
        "Sorcerer",
        "Warlock",
        "Wizard",
    )
}

This allows you to easily look up a class by its name, so you can do things like:

try:
    char_class = dnd_classes[input("Pick a class: ")]
except KeyError:
    print("Class must be one of:", ", ".join(dnd_classes))

instead of:

user_class = input("Pick a class" )
if user_class == "Barbarian":
    char_class = Barbarian
elif user_class == "Bard":
    # ugggggh
  • Related