试图在python中添加值但是出现int不可调用的错误

时间:2016-07-08 12:28:26

标签: python class python-3.x int

我试图在python中添加一个类中的多个整数但是它会出现错误:

  

追踪(最近一次通话):         文件“G:/ documents / Computing / Python / Fighter Game.py”,第53行,in           如果player.health()+ player.strength()+ player.defence()+ player.speed()== 350:       TypeError:'int'对象不可调用

该课程的代码是:

class Fighter:
    name = "Not Set"
    alignment = "Not Set" #good / bad
    health = 0
    strength = 0
    defence = 0
    speed = 0
    def name(self):
        return self.name
    def alignment(self):
        return self.alignment
    def health(self):
        return self.health
    def strength(self):
        return self.strength
    def defence(self):
        return self.defence
    def speed(self):
        return self.speed
    def set_name(self, new_name):
        self.name = new_name
    def set_alignment(self, new_alignment):
        self.alignment = new_alignment
    def set_health(self, new_health):
        self.health = new_health
    def set_strength(self, new_strength):
        self.strength = new_strength
    def set_defence(self, new_defence):
        self.defence = new_defence
    def set_speed(self, new_speed):
        self.speed = new_speed

并且抛出错误的代码是:

player = Fighter()
while True:
    player.set_name(input("Enter your name: "))
    player.set_alignment("good")
    player.set_health(int(input("Enter your health: ")))
    player.set_strength(int(input("Enter your strength: ")))
    player.set_defence(int(input("Enter your defence: ")))
    player.set_speed(int(input("Enter your speed: ")))
    if player.health() + player.strength() + player.defence() + player.speed() == 350:
        print("Player setup complete.")
        break
    else:
        print("Numerical player values must all add up to 350.")

任何可以给予的帮助将不胜感激! : - )

1 个答案:

答案 0 :(得分:4)

您有两件名为self.health的东西;整数和方法。这没有意义。

实例变量通常以_为前缀,并在__init__()中设置,至少这是"老派"简单的方法:

def __init__(self):
  self._health = 40

def health(self):
   return self._health

等等。但是,请查看属性和属性,以获得更优雅的方法。