【问题标题】:Referencing Class properties with variables in Python 2.7在 Python 2.7 中使用变量引用类属性
【发布时间】:2015-03-04 04:00:53
【问题描述】:

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

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

【问题讨论】:

  • 这不是你使用类的方式。

标签: python class variables


【解决方案1】:

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

【讨论】:

  • 所以如果用户输入“cannon”,这会对碰巧是敌人的人造成4点伤害?另外,这可以与布尔值一起使用吗?我有一个自有属性。
  • 另外,namedtuple 是做什么的?
【解决方案2】:

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

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


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2015-11-03
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多