Python-TypeError:“int”对象不是callab

2024-06-12 06:44:42 发布

您现在位置:Python中文网/ 问答频道 /正文

(使用Python2.7)

你好

我有两个版本的一个类PairOfDice。

1.)此操作不起作用并引发错误。

TypeError: 'int' object is not callable

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()

请有人解释一下第一个有什么问题吗?

谢谢


Tags: ofthenameimportselfreturndefrandom
2条回答

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

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

您可能需要将total函数重命名为类似于getTotal或类似的名称。

在第一个类中,total是类的函数和属性。这是不好的:)Python认为您在最后一行中引用的总数是整型变量total,而不是函数。

将函数total命名为get_total是一种很好的做法

相关问题 更多 >