【发布时间】: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方法;您在第一个示例的最后一行调用了该号码。一个类实例只有一个命名空间,包括值和方法。