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

Referencing Class properties with variables in Python 2.7

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

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

您可以使用简单的 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

制作武器,敌人class并在战斗之前启动()

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


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