在 class 中调用对象时 Int 对象不可调用

Int object is not callable when calling an object within a class

我正在制作一个有 2 艘飞船战斗的程序。到目前为止它正在工作但是当我们调用攻击函数时我们得到这个错误:

"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), random.randint(0, 255))
color2 = (random.randint(0, 255), random.randint(0, 255), 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),random.randrange(10,200),-250,50)
Noob.draw_spaceship(color1)

Pro = spaceship("Pro",random.randrange(100,1000),random.randrange(100,500),random.randrange(10,200),100,50)
Pro.draw_spaceship(color2)

drawer.forward(2000)

Pro.attack(color1, Noob)

尝试将方法重命名为“攻击”,然后重试。似乎用相同的名称调用了一个属性和一个方法。

问题是您声明 spaceship 的属性(变量)attack 与其方法 ​​attack() 相同。
由于 Prospaceship 的一个实例,当您在脚本末尾调用 Pro.attack() 时,您实际上是在尝试调用其 int[=22= 类型的属性].

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