0

I am trying to modify a variable based on user input. For example if the user wanted to change their strength variable they would type in "strength" and then that variable (tied to a player object so in this example player.strength) would be reassigned the new value.

I have attempted using dictionaries to hold the variable name as this is what I've used to call functions/methods as well but after browsing here a bit have realized this will not work due to it being immutable.

My current attempt looks like this:

skill_dict = {"Swords": self.swords}
answer = input("Which skill would you like to be proficient in?")
skill_dict[answer] += 10
print(skill_dict[answer])
print(self.swords)

The output however shows that this not work with the dictionary value being changed to 10 while the actual variable value remaining unchanged.

Is there a way to do this?

wjandrea
  • 28,235
  • 9
  • 60
  • 81

1 Answers1

0

Use a dict to contain all the player's stats, like this:

class Player:
    def __init__(self, swords, strength):
        self.skills = {'swords': swords, 'strength': strength}

    def become_proficient(self):
        answer = input("Which skill would you like to be proficient in? ")
        self.skills[answer] += 10
        print(self.skills[answer])

Example run:

>>> player = Player(5, 6)
>>> player.become_proficient()
Which skill would you like to be proficient in? swords
15
>>> player.become_proficient()
Which skill would you like to be proficient in? strength
16
>>> player.skills
{'swords': 15, 'strength': 16}

On the other hand, if you need to use attributes, you can use setattr() and getattr(), but this allows the user access to any attributes, which is generally a bad idea.

answer = input("Which skill would you like to be proficient in? ")
setattr(self, answer) = getattr(self, answer) + 10
wjandrea
  • 28,235
  • 9
  • 60
  • 81