(使用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()
请有人解释一下第一个有什么问题吗?
谢谢
这是因为您有一个名为total的属性,以及一个名为
total
的函数。运行roll
时,将覆盖类的total
定义。换句话说,在运行
roll
之前,player1.total
是一个函数。但是,一旦运行roll,就将player1.total
设置为一个数字。从那时起,当你引用player1.total
时,你指的就是那个数字。您可能需要将
total
函数重命名为类似于getTotal
或类似的名称。在第一个类中,
total
是类的函数和属性。这是不好的:)Python认为您在最后一行中引用的总数是整型变量total,而不是函数。将函数
total
命名为get_total
是一种很好的做法相关问题 更多 >
编程相关推荐