在类中调用对象时,不能调用Int对象

问题描述

我正在制作一个有2艘太空飞船战斗的程序。到目前为止,它仍然有效,但是当我们调用Attack函数时,会出现以下错误

"TypeError: 'int' object is not callable on line 54"

我花了一些时间进行调试,但无法弄清楚哪里出了问题。这是代码:请提供一些建议使其生效

import turtle
import time
import random
drawer = turtle.Turtle()
drawer.shape("square")
drawer.speed(0)
attacker = turtle.Turtle()
attacker.shape("square")
attacker.speed(0.5)
attacker.penup()

color1 = (random.randint(0,255),random.randint(0,255))
color2 = (random.randint(0,255))

class spaceship:
  def __init__(self,name,health,attack,sheild,x,y):
    self.name = name
    self.health = health
    self.attack = attack
    self.sheild = sheild
    self.x = x
    self.y = y
  def draw_spaceship(self,color):
    drawer.color(color)
    drawer.penup()
    drawer.goto(self.x,self.y)
    drawer.begin_fill()
    for i in range(0,4):
      drawer.forward(100)
      drawer.right(90)
    drawer.end_fill()
  def attack(self,color,enemy_name):
    attacker.goto(self.x,self.y)
    attacker.goto(enemy_name.x,enemy_name.y)
    attacker.color(color)
    where_attack = random.randrange(0,2)
    if where_attack == 1:
      where_attack = "health"
      enemy_name.health -= self.attack
    else:
      where_attack = "sheild"
      enemy_name.sheild -= self.attack
    print(self.name,"is attacking the",where_attack,"of",enemy_name.name+".")
    print("Now",enemy_name.name,"has",enemy_name.health,"health.")

# draws spaceships
Noob = spaceship("Noob",random.randrange(100,500),random.randrange(10,200),-250,50)
Noob.draw_spaceship(color1)

Pro = spaceship("Pro",1000),100,50)
Pro.draw_spaceship(color2)

drawer.forward(2000)

Pro.attack(color1,Noob)

解决方法

尝试重命名方法“攻击”,然后重试。似乎属性和方法使用相同的名称来调用。

,

问题是您要声明spaceship的属性(变量)attack与方法attack()相同。
由于Prospaceship的实例,因此当您在脚本末尾调用Pro.attack()时,实际上是在尝试调用其类型为 int 的属性。 / p>

尝试将方法的名称更改为其他名称