如何在Python中“动态”分配类变量?

时间:2018-12-16 10:01:48

标签: python class object variables

我有以下代码:

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.healthplayer.staminaplayer.mana分配给potion.var

4 个答案:

答案 0 :(得分:2)

之所以不起作用,是因为您已经将参数player.health传递给了药水,这与编写相同:

Potion("Health potion",100,50)

答案 1 :(得分:1)

class Potion():
    def __init__(self,name,var,varamount):
        self.name=name
        self.var=var
        self.varamount=varamount

class Inventory():
    def __init__(self):
        self.items={}

    def add_item(self, item):
        if item in self.items.keys():
            self.items[item] += 1
        else:
            self.items[item] = 1
        print ('Added a {} potion!'.format(item.name)

    def remove_item(self, item):
        if item in self.items.keys():
            self.items[item] -= 1
            return True
        else:
            print ('No such {} exists!'.format(item.name))
            return False


class Player():
    def __init__(self):
        self.health=100
        self.mana=100
        self.stamina=100
        self.inventory = Inventory()

    def use_item(self, item):
        if isinstance(item, Potion):
            if self.inventory.remove_item(item):
                if item.var == 'health':
                    self.health += item.varamount
                    print ('Used a {0} and healed {1}!'.format(item.name, item.varamount))

player=Player()
healthpotion=Potion("Health potion", 'health', 50)
player.use_item(healthpotion)
player.inventory.add_item(healthpotion)
player.use_item(healthpotion)

#No such Health potion exists!
#Added a health potion!
#Used a Health potion and healed 50!

您需要首先考虑对象的工作方式。

库存是使用药水,还是玩家使用药水?

在提供的代码中,我使Player类拥有自己的清单。然后,播放器可以使用添加到其自身库存中的药水。

答案 2 :(得分:0)

您需要发送创建的Player实例,而不仅仅是其属性的值:

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):
        # Your potion.var contains Player instance. Access players health.
        potion.var.health += 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,50) # Send player instance.
print(player.health) # 100
inventory.use_potion(healthpotion)
print(player.health) # 150

答案 3 :(得分:0)

您正在使用对象。对象“知道”事物(其服装的值),并且对象可以通过调用其方法相互发送消息。

在这种情况下:

  • Player知道他们的健康。
  • Potion知道它可以在多大程度上改善健康状况
  • Inventory知道它是否有药。
  • Player应该有一个清单
  • Player可以选择使用其库存中的物品
  • Inventory跟踪是否已使用某项

基于这些事实,我们知道我们的类需要哪些方法和属性。

药水需要知道可以恢复多少个健康点

class Potion(object):

    def __init__(self,name, varamount):
        self.name=name
        self.varamount=varamount

库存需要能够跟踪其内容。

class Inventory(object):
    def __init__(self):
        self.items={}

    def add_potion(self, potion):
        self.items['potion'] = potion

    def get_potion(self):
         return self.items.get('potion')

    def remove_potion(self):
        self.items.pop('potion', None)

玩家需要能够跟踪其健康状况并使用药水。

class Player():
    def __init__(self, inventory):
        self.health=100
        self.mana=100
        self.stamina=100
        self.inventory = inventory

    def use_potion(self):
        potion = self.inventory.get_potion()
        if potion:
            self.health += potion.varamount
            self.inventory.remove_potion()
        print("Used a ",potion.name," !")

inventory=Inventory()

healthpotion=Potion("Health potion", 50)
inventory.add_potion(healthpotion)

player=Player(inventory)
player.use_potion()
相关问题