【发布时间】:2018-06-30 10:57:43
【问题描述】:
我正在尝试创建一个带有 DiceShaker() 子类的 Die() 类。 DiceShaker() 子类应该获取 Die() 类的多个副本,滚动它们,然后返回各个滚动。这是我的 Die() 代码。
class Die(object):
'a class representing a Die'
def __init__(self, sides=6):
'initialize a die, default 6 sides'
self.sides = sides
def roll(self):
'roll the dice'
self.dieRoll = random.randint(1, self.sides)
def get(self):
'get the current value of the die'
return self.dieRoll
这是我的 DiceShaker() 代码。
class DiceShaker(Die):
'DiceShaker class'
def __init__(self,dieCount=1, dieSides=6, dieList = [], dieList2 = []):
'initialize a dice shaker'
Die.__init__(self,sides = 6)
self.dieCount = dieCount
self.dieSides = dieSides
self.dieList = dieList
self.dieList2 = dieList2
def shake(self):
'shake all the dice in the shaker'
counter = 0
dieList = []
while counter != self.dieCount:
self.dieList.append(Die.roll(self))
counter = counter + 1
return self.dieList
def getIndividualRolls(self):
'get a lsit of integers of all the individual die rolls'
for items in self.dieList:
self.dieList2.append(Die.get(self))
return self.dieList2
getIndividualRolls() 应该返回一个包含所有通过shake() 的骰子的列表,但打印的列表总是只有一个数字。 示例:
d=DiceShaker(3)
d.shake()
[None, None, None]
d.getIndividualRolls()
[3, 3, 3]
我有 Shake() 返回 [none] 只是为了知道正确数量的骰子正在通过,但我无法弄清楚为什么 getIndividualRolls() 会不断打印出重复的骰子。谁能帮我弄清楚我做错了什么?
【问题讨论】:
-
为什么你的
DiceShaker是Die的子类?这是没有意义的。子类化用于is a关系。DiceShaker不是Die的类型(就像ShoppingCart不是CartItem的类型。你的关系是组合的。DiceShaker有Dies(你用@987654334 反映) @)。 -
如果您有选择,您应该学习 Python 3。Python 2 即将退出:pythonclock.org
标签: python list class return subclass