Python:函数不返回任何值

时间:2017-07-02 04:14:21

标签: python-3.x

我需要调用attack()checkLife()函数,但这些函数不会返回任何值。我该怎么做才能解决这个问题?

class Enemy: life = 100


    def choose(self,ch):
        return {1:self.attack,
                2:self.checkLife
                }[ch]


    def attack(self):
        print('ouch!')
        self.life-=1

    def checkLife(self):
        if(self.life <= 0):
            print('I am dead')
        else:
            print(str(self.life) + "Life Left...")

enemy1 = Enemy()
enemy1.choose(1)

1 个答案:

答案 0 :(得分:1)

您忘记添加括号()

class Enemy: 
  life = 100
  def choose(self,ch):
    return {1:self.attack(), #here
            2:self.checkLife() #and here
            }[ch]


  def attack(self):
    print('ouch!')
    self.life-=1

  def checkLife(self):
    if(self.life <= 0):
        print('I am dead')
    else:
        print(str(self.life) + "Life Left...")

enemy1 = Enemy()
enemy1.choose(1)