反复从类对象(Python)中的列表中删除项目
问题描述:
如何从Python 3中重复删除列表中的项目?对于我的代码工作的第一个项目,但如果我尝试应用再次删除项目的方法,它会生成TypeError
。这里是我一起工作的代码:反复从类对象(Python)中的列表中删除项目
十一点游戏
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()
功能,例如在混洗的full_deck
上使用pop()
,也会发生相同的错误。
答
您正在用绘制的卡片覆盖Black_jack_deck.draw()
方法。因此关于deck.draw()
的错误是'str' object
和is 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'
+0
与记忆的东西将在晚些时候。现在我只是想让卡片绘制工作。有了布尔参数,我认为这是必要的。感谢你的回答,它非常帮助我:-) –
请发布格式正确的代码。在Python中,空格在语法上很重要,并且按照这种方式,它不起作用。 – Morgoth
您似乎有一个名为'self.draw'的函数和变量。你如何期待Python知道你的意思? – Craig
Python“知道”它是哪一个:它是最后一个被设置的。你会*覆盖另一个。 –