在Python 2.7中使用变量引用类属性

时间:2015-03-04 04:00:53

标签: python class variables

我正在开发基于文本的游戏,但我还没有找到一个非常有效的解决方案来解决我的战斗系统问题。我目前的语句设置如下:

class Weapon1:
    damage = 4
    price = 5

class Weapon2:
    damage = 4
    price = 5

class Enemy1:
    damage = 2
    health = 5

class enemy2:
    damage = 3
    health = 6

def fight():
    Weapon = raw_input("What weapon would you like to use?")
    if Weapon == "Weapon 1":
        if enemy = "Enemy1":
            Enemy1.health -= Weapon1.damage
        else:
            Enemy2.health -= Weapon1.damage
    else:
        if enemy = "Enemy1":
            pass
        else:
            pass

我有比这更多的敌人和类,所以我想有一个可以引用类的单一语句'使用变量的属性。我决定不上传实际功能,因为它超过100行。 我之后的伪代码看起来像这样:

class pistol:
    damage = 4
    price = 5

class cannon:
    damage = 4
    price = 5

class Enemy1:
    damage = 2
    health = 5

class enemy2:
    damage = 3
    health = 6

def fight():
    Weapon = raw_input("What weapon would you like to use?")
    enemy.health -= weapon.damage

2 个答案:

答案 0 :(得分:2)

您可以使用简单的dict,此处使用namedtuple以使代码更易于阅读:

from collections import namedtuple

Weapon = namedtuple('Weapon', ['damage', 'price'])

weapons = {
    'pistol': Weapon(4, 5),
    'cannon': Weapon(4, 5),
    # ...
}

def fight():
    weapon_name = raw_input("What weapon would you like to use?")
    enemy.health -= weapons[weapon_name].damage

答案 1 :(得分:1)

制造武器,敌人类并在战斗前启动()

class weapon:
  def __init__(self,d,p):
      self.damage = d
      self.price = p


def initiate():
    pistol = weapon(4,5)
    #....