重复从类对象(Python)中的列表中删除项

时间:2017-04-26 20:59:37

标签: python list class oop methods

如何在Python 3中重复删除列表中的项目?对于我的代码的第一个项目,但如果我尝试应用再次删除项目的方法,它会生成TypeError。这是我正在使用的代码:

BlackJack游戏

from random import choice

class Black_jack_deck(object):

    def __init__(self, full_deck=(([str(i) for i in range(2,11)]+["A","J","Q","K"])*4*6)): #a deck of 312 cards containing 6* 52 french cards
        self.full_deck = full_deck

    def draw(self, draw=True):
        self.draw = choice(self.full_deck)   #I use choice to simulate the dealer drawing a card from the top of a mixed card staple
        return self.draw
        self.full_deck = (self.full_deck).remove(self.draw)   


deck = Black_jack_deck() 

我尝试第二次调用deck.draw()时产生的错误如下所示:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    deck.draw()
TypeError: 'str' object is not callable

注意:即使没有choice()函数,例如在混合pop()上使用full_deck,也会发生同样的错误。

1 个答案:

答案 0 :(得分:1)

您使用卡片覆盖了Black_jack_deck.draw()方法。因此,deck.draw()的错误是'str' objectis not callable

这是一个较短的版本。你需要记住鞋子里的卡片吗?我删除了draw()的布尔参数,因为我不知道它为什么存在。

In [94]: class CardShoe(object):
    ...:     def __init__(self, num_decks=6):
    ...:         self.cards = list('A23456789JQK' * 4 * num_decks)
    ...:         random.shuffle(self.cards)
    ...:
    ...:     def draw(self):
    ...:         self.last_card_drawn = self.cards.pop()
    ...:         return self.last_card_drawn
    ...:

In [95]: shoe = CardShoe()

In [96]: shoe.draw()
Out[96]: '2'

In [97]: shoe.draw()
Out[97]: '8'