我无法理解这个Python程序中的错误

时间:2018-01-20 18:17:50

标签: python python-3.x

我无法在此找到错误。它给出的错误是您没有创建函数life_left,或者它无法找到它。

你想让他们打多少次? 5

错误:

Traceback (most recent call last):    
  File "main.py", line 42, in <module>    
    start(7)    
  File "main.py", line 39, in start    
    arr[number].attack(guns[guns_number])    
  File "main.py", line 19, in attack    
    life_left(self.life)    
 NameError: name 'life_left' is not defined

代码:

import random
class Enemy:
    def __init__(self):
        self.life = 20

    def attack(self,gun):
        if (self.life <= 0):
            print("Dead")
        else:
            if gun is "AK47":
                self.life = self.life - 5
                life_left(self.life)
            elif gun is "Magnum":
                self.life = self.life - 4
                life_left(self.life)
            else:
                self.life = self.life - 1
                life_left(self.life)

    def life_left(life):
         print ("Life  :  " , str(life))


def start(players):
    a = 1
    arr = []
    while a <= players:
    arr.append("player" + str(a))
    arr[a-1] = Enemy()
    #print (arr[a-1])
    a += 1
    enemy = int(input("How many times do you want them to fight ? "))
    fight = 1
    guns = ["AK47" , "Magnum" , "other"]
    while fight <= enemy:
        number = random.randint(0,players-1)
        guns_number = random.randint(0,len(guns)-1)
        arr[number].attack(guns[guns_number])
        fight += 1
start(7)

1 个答案:

答案 0 :(得分:0)

您必须在方法定义中使用self并调用类中的方法。这是固定代码:

import random
class Enemy:
    def __init__(self):
        self.life = 20

    def attack(self,gun):
        if (self.life <= 0):
            print("Dead")
        else:
            if gun is "AK47":
                self.life = self.life - 5
                self.life_left(self.life)
            elif gun is "Magnum":
                self.life = self.life - 4
                self.life_left(self.life)
            else:
                self.life = self.life - 1
                self.life_left(self.life)

    def life_left(self,life):
         print ("Life  :  " , str(life))


def start(players):
    a = 1
    arr = []
    while a <= players:
        arr.append("player" + str(a))
        arr[a-1] = Enemy()
        #print (arr[a-1])
        a += 1
    enemy = int(input("How many times do you want them to fight ? "))
    fight = 1
    guns = ["AK47" , "Magnum" , "other"]
    while fight <= enemy:
        number = random.randint(0,players-1)
        guns_number = random.randint(0,len(guns)-1)
        arr[number].attack(guns[guns_number])
        fight += 1
start(7)