繁体   English   中英

Python-TypeError:“ int”对象不可调用

[英]Python - TypeError: 'int' object is not callable

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

请问有人可以解释第一个问题吗?

谢谢

在第一类中, total是该类的功能和属性。 那不行:) Python认为最后一行中引用的总数是整数变量total而不是函数。

最好将函数total命名为get_total这是一个好习惯

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM