0

I'm trying to use a member function to change a variable, but would like the function to accept any variable, not create a new function for each one. How would I do this?

class Player:
    def __init__(self, name=None, armor=None, maxHP=None, currentHP=None):
        self.name = name
        self.armor = armor
        self.maxHP = maxHP
        self.currentHP = currentHP
    
    def setStat(self, stat, value):
        self.stat = value #Not valid Code, what should I change



John = Player(armor=5)

print(John.armor)

#This of course throws an error, but I'd like it to print 5 and then 10
John.setStat(armor, 10)
    
print(John.armor)
        
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Does this answer your question? https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute – Iain Shelvington Sep 24 '22 at 23:53
  • Does this answer your question? [What's the pythonic way to use getters and setters?](/q/2627002/4518341), particularly [Aaron's answer](/a/36943813/4518341). In short, don't use a setter, just change the attributes directly. – wjandrea Sep 24 '22 at 23:56

0 Answers0