Python 3 - 如何使用循环一次创建多个 类?

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

我正在尝试制作一个 D&D 角色创建器,尽管我需要为其中的每个 'class' 和 'race' 创建一个 class 的单独实例。

我已经做到了,每个实例都是在单独的一行上创建的,一个接一个(所以现在大约有 45 行,包括注释),但是,我想知道我是否可以创建一个循环来创建所有只需几行代码即可完成实例。

我查看了其他回复,尽管其中 none 非常有效地完成了我想做的事情,所以我希望有人能在这里帮助我。

现在的代码如下所示:

## 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")

我建议将您的 classes 收集到以 class 名称为关键字的字典中,而不是为每个命名变量:

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

这使您可以通过名称轻松查找 class,因此您可以执行以下操作:

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

而不是:

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