获取错误列表不可调用

时间:2016-12-23 12:41:36

标签: python

我正试图从牌组中取出一张随机牌。

import itertools, random
from random import randint
class card:
    __deck = list(itertools.product(range(1,14),['s','h','d','c']))
    def getCard(self):
        randCard = self.__deck(randint(0,52))
        return randcard
card = card()
print card.getCard()

返回:TypeError: 'list' object is not callable

2 个答案:

答案 0 :(得分:1)

self.__deck(randint(0,52))尝试调用列表self.__deck,这当然不可调用。

要访问列表的元素,请使用:

self.__deck[randint(0,52)]

假设return randcard是拼写错误,因为它应该是return randCard

答案 1 :(得分:0)

问题是行randCard = self.__deck(randint(0,52))

您所做的是使用括号而不是方括号:

randCard = self.__deck(randint(0,52))
\/
randCard = self.__deck[randint(0,52)]

您在第二个randCard中也有一个小写字母,我在下面的代码中为您修复了这个小写字母。 新代码:

import itertools, random
from random import randint
class card:
    __deck = list(itertools.product(range(1,14),['s','h','d','c']))
    def getCard(self):
        randCard = self.__deck[randint(0,51)] # This line was creating the error. Also randint will return a value from 0 to 52 included so its a good idea to change it to randint(0, 51)
        return randCard
card = card()
print card.getCard()

方括号用于访问数组索引,而括号用于调用函数,这就是错误表示您正在尝试调用列表的原因。