简体   繁体   中英

How to use a list of strings as variable names/object attributes?

What I'd like to do is have a list of strings be used as attributes of an object when it is created. I've seen another topic discuss using a list of strings as variables by creating a dictionary, but this seems to keep the strings as strings, which won't work for me, I don't think. Here's what I would like to work. It's a DnD exercise:

abilities = ['strength', 'dexterity', 'constitution', 'intelligence', 'wisdom', 'charisma']


class Character:
    def __init__(self):
        for ability in abilities:
            self.ability = roll_ability()       #this is a call to an outside function

Thanks!

Use setattr :

def __init__(self):
    for ability in abilities:
        setattr(self, ability, roll_ability())

Since this is for a D&D game, it's likely you will need to access the ability scores dynamically too; for example, a saving_throw method could take the name of the ability you are using to roll a saving throw . In that case, it is usually a better design to use a dictionary instead of separate attributes:

class Character:
    def __init__(self):
        self.abilities = { ability: roll_ability() for ability in abilities }

    def get_ability_score(self, ability):
        return self.abilities[ability]

    def saving_throw(self, ability, bonus=0):
        return roll_dice(20) + self.abilities[ability] + bonus

This can be yet another option to go with avoiding using global vars:

class Something:

    def __init__(self, *args):
        for ability in args:
            setattr(self, ability, roll_ability())


abilities = ['strength', 'dexterity', 'constitution', 'intelligence', 'wisdom', 'charisma']
s = Something(*abilities)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM