随机随机错误消息

时间:2017-06-20 20:30:43

标签: python random

您好我正在写一个Monopoly游戏模拟器,并有以下列表 卡片对象中的公益金卡号: -

self.CChcards_MessNo = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

我希望使用以下方法来改组这些

def shuffle(self):
   import random
   random.shuffle(self.CChcards_MessNo)

在程序的早期工作,但失败并给出 稍后将在程序的主要部分中显示以下消息。

  File "C:\Users\David\AppData\Local\Programs\Python\Python35\lib\random.py", line 278, in shuffle
    for i in reversed(range(1, len(x))):
TypeError: object of type 'int' has no len()

当程序循环显示16张牌并且现在需要随机播放时会发生这种情况

1 个答案:

答案 0 :(得分:1)

>>> class Foo():
...     def __init__(self):
...         self.CChcards_MessNo = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
...     def shuffle(self):
...         import random
...         random.shuffle(self.CChcards_MessNo)
...     def bug(self):
...         print("I'm a bug that makes shuffle() fail by assigning an int to self.CChcards_MessNo")
...         self.CChcards_MessNo = 0
...
>>> foo = Foo()
>>> foo.shuffle()
>>> foo.bug()
I'm a bug that makes shuffle() fail by assigning an int to self.CChcards_MessNo
>>> foo.shuffle()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in shuffle
  File "C:\Program Files (x86)\Python36-32\lib\random.py", line 271, in shuffle
    for i in reversed(range(1, len(x))):
TypeError: object of type 'int' has no len()