[英]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.