缺少Python类属性

时间:2019-04-14 16:13:13

标签: python

我正在用python开发游戏。我在代码中遇到了一些问题。我将暴民定义为不同的类,以便以后轻松编辑。我遇到的问题是,我无法要求健康对其造成损害。

class spaceStalker(object):
  def __init__(self, name, hp):
    self.name = name
    self.hp = hp
mobList = [spaceStalker]
mob = random.choice(mobList)
killList = ["not killed the beast!", "killed the beast!"]
kill = random.choice(killList)
def game():
  if mob == spaceStalker:
    fleeAtt = input("A Space Stalker has appeared! Attack or flee? ")
    if fleeAtt == "Attack":
      hitPass = input("Attack or Pass? ")
      if hitPass == "Attack":
        spaceStalker.hp -= 50
        print(spaceStalker.hp)
  else:
    print("1")```

1 个答案:

答案 0 :(得分:0)

使用类的实例

mobList = [SpaceStalker('some name', 54)]

当您进行生物检测时,您可以使用isinstance(object, classname)进行操作:

所以而不是:

if mob == spaceStalker:
  #dosomething

使用:

if isinstance(mob, SpaceStalker):
  #dosomething

我还建议您在课堂上使用getter和setter:

class SpaceStalker(object):
  def __init__(self, name, hp):
    self.name = name
    self.hp = hp

  @property
  def hp(self):
    return self.__hp

  @hp.setter
  def hp(self, hp):
    #some validation here
    self.__hp = hp

另外,也许您想使用类名约定(驼峰式),所以我将其写为SpaceStalker