I have the following code :
class Potion(object):
def __init__(self,name,var,varamount):
self.name=name
self.var=var
self.varamount=varamount
class Inventory(object):
def __init__(self):
self.items={}
def use_potion(self,potion):
potion.var+=potion.varamount
print("Used a ",potion.name," !")
class Player():
def __init__(self):
self.health=100
self.mana=100
self.stamina=100
inventory=Inventory()
player=Player()
healthpotion=Potion("Health potion",player.health,50)
inventory.use_potion(healthpotion)
Here, my health potion is supposed to add 50 to the variable player.health.
But player.health remains unchanged, only healthpotion.var is changed.
Assuming I want different types of potions (stamina, mana, health), how can I dynamically assign player.health, player.stamina and player.mana to potion.var ?
print(healthpotion.var)it prints150so it is working. I'd suggest you test and come back with the exact question you had in mind.potion.var+=potion.varamount, you meansetattr(player, potion.var, getattr(player, potion.var) + potion.varamount)wherepotion.var == "health"?player.healthis evaluated to100when you send it to thePotionconstructor. It doesn't persist as a pointer or reference to that variable.