【问题标题】:Python - TypeError: 'int' object is not callablePython - TypeError:'int'对象不可调用
【发布时间】:2017-12-20 15:01:55
【问题描述】:

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

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

谢谢

【问题讨论】:

  • self.total赋值会覆盖self.total方法;您在第一个示例的最后一行调用了该号码。一个类实例只有一个命名空间,包括值和方法。

标签: python class typeerror


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    在第一个类中total 是一个函数以及类的一个属性。这不行 :) Python 认为你在最后一行中引用的总数是整数变量 total 而不是函数。

    将函数 total 命名为 get_total 被认为是一种好习惯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 2012-04-03
      • 1970-01-01
      相关资源
      最近更新 更多