我有以下代码:
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)
在这里,我的健康药水应该为变量
player.health
加50。但是
player.health
保持不变,只有healthpotion.var
被更改。假设我想要不同类型的药水(耐力,法力值,生命值),如何动态地将
player.health
,player.stamina
和player.mana
分配给potion.var
? 最佳答案
这样做不起作用的原因是您已将参数player.health传递给了Potion,这与编写相同:
Potion("Health potion",100,50)
关于python - 如何在Python中“动态”分配类变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53801141/