Python - TypeError:' int'对象不可调用

时间:2017-07-15 17:48:31

标签: python class typeerror

(使用Python 2.7)

你好,

我有两个版本的PairOfDice。

1。)这个不起作用并抛出错误。

  

TypeError:' int'对象不可调用

import random

class PairOfDice:
    """ Represent the Pair of Dices and have method which tells the total of those roles.
    """
    def roll(self):
        self.total = random.randint(1, 6) + random.randint(1, 6)

    def total(self):
        return self.total

    def name(self, name):
        self.name = name

    def getName(self):
        return self.name

player1 = PairOfDice()
player1.roll()
print player1.total()

2)这个正在运作。

import random

class PairOfDice:
    """ Represent the Pair of Dices and have method which tells the  total of those roles.
    """
    def roll(self):
        self.roll1 = random.randint(1, 6)
        self.roll2 = random.randint(1, 6)

    def total(self):
        return self.roll1 + self.roll2

    def name(self, name):
        self.name = name

    def getName(self):
        return self.name

player1 = PairOfDice()
player1.roll()
print player1.total()

可以请某人解释第一个错误吗?

由于

2 个答案:

答案 0 :(得分:3)

在第一个类中,total是一个函数,也是类的一个属性。那不太好:) Python认为你在最后一行中所指的总数是整数变量total而不是函数。

将函数total命名为get_total而不是

是一种很好的做法

答案 1 :(得分:3)

这是因为你有一个名为total的属性,以及一个名为total的函数。当您运行roll时,您将覆盖该班级对total的定义。

换句话说,在运行roll之前,player1.total是一个函数。但是,一旦运行roll,就将player1.total设置为数字。从那时起,当您引用player1.total时,您指的是该数字。

您可能希望将total函数重命名为getTotal或类似名称。