类中的Python方法

类中的Python方法,python,class,methods,Python,Class,Methods,我正在尝试正确地使用对象,我已经建立了一副卡片,这是我的对象。我希望能够洗牌和发牌从它。然而,我不知道如何让shuffle方法正确工作,或者即使这是最好的方法 import itertools import random class Deck: '''Deck of cards to be used in a card game''' def __init__(self): self.faces = ['A', 'K', 'Q', 'J', 'T', '9',

我正在尝试正确地使用对象,我已经建立了一副卡片,这是我的对象。我希望能够洗牌和发牌从它。然而,我不知道如何让shuffle方法正确工作,或者即使这是最好的方法

import itertools
import random

class Deck:
    '''Deck of cards to be used in a card game'''
    def __init__(self):
        self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
        self.suits = ['c', 'd', 'h', 's']
        self.cards = set(itertools.product(self.faces, self.suits))

    def shuffle(self):
        self.cards = random.shuffle(self.cards)

    def deal(self):
        card = self.cards.pop()
        return card[0] + card[1]
用法

deck = Deck()
deck.shuffle()
deck.deal()

集合
未排序,您可以使用
list()
获得排序的组。 此外,
random.shuffle(l)
直接作用于列表并返回
None
,因此您将使用
None
覆盖列表

import itertools
import random

class Deck:
    '''Deck of cards to be used in a card game'''
    def __init__(self):
        self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
        self.suits = ['c', 'd', 'h', 's']
        self.cards = list(itertools.product(self.faces, self.suits))  # ordered deck
        # self.cards = set(itertools.product(self.faces, self.suits))  # unordered deck

    def shuffle(self):
        random.shuffle(self.cards)

    def deal(self):
        card = self.cards.pop()
        return card[0] + card[1]

应该使用
list
而不是
set
random。shuffle
在适当的位置修改列表;它返回
None
,而不是无序列表。列表和无序就地工作。谢谢各位,根本不需要
set
,因为
product
不会产生任何需要删除的副本。它只需要
list
set
之间的一个。它不需要
列表(set(…)
,感谢您指出它