首页 > 解决方案 > 嵌套 Dealer::Card::Deck 类 Deck.cards 在 build 方法期间获取列表,但在 shuffle 方法期间列表消失

问题描述

我已经稍微简化了代码,因为它是更大的烧瓶项目的一部分。但是问题仍然存在:

import random
class Dealer:
    def __init__(self):
        self.deck = self.Deck()
    class Deck:
        def __init__(self):
            self.cards = []
            self.cards = self.build()
        def build(self):
            for suit in ['Spades', 'Diamonds', 'Hearts', 'Clubs']:
                if suit == 'Spades':
                    suit_url='S.png'
                elif suit == 'Diamonds':
                    suit_url="D.png"
                elif suit == "Hearts":
                    suit_url="H.png"
                elif suit == "Clubs":
                    suit_url="C.png"
                for val in [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]:
                    img_url = (str(val) + suit_url)
                    self.cards.append(self.Card(val, suit, img_url))
        def shuffle(self):
            for i in range(len(self.cards)-1, 0, -1):
                rand_num = random.randint(0, i)
                self.cards[i], self.cards[rand_num] = self.cards[rand_num], self.cards[i]
        class Card:
            def __init__(self, value, suit, img):
                self.value = value
                self.suit = suit
                self.img = img                
dealer = Dealer()
deck = dealer.Deck()
deck.shuffle()

卡片列表在 Deck 构建方法中显示了卡片对象的有效列表,但是当它到达 shuffle 方法时,卡片在调试器中显示没有?

标签: classnestedattributespython-3.8nonetype

解决方案


怎么了:

'self.build()' 方法不返回任何东西(VOID)它只是更新'self.cards'。但是'self.cards' 与'self.build()' 的输出相当。但是输出没有,当你想使用'deck.shuffle()'时,你试图得到无的长度。

怎么修:

只需调用 build 方法来填充卡片。

import random
class Dealer:
    def __init__(self):
        self.deck = self.Deck()
    class Deck:
        def __init__(self):
            self.cards = []
            # Just call build method to fill the cards
            self.build()
        def build(self):
            for suit in ['Spades', 'Diamonds', 'Hearts', 'Clubs']:
                if suit == 'Spades':
                    suit_url='S.png'
                elif suit == 'Diamonds':
                    suit_url="D.png"
                elif suit == "Hearts":
                    suit_url="H.png"
                elif suit == "Clubs":
                    suit_url="C.png"
                for val in [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]:
                    img_url = (str(val) + suit_url)
                    self.cards.append(self.Card(val, suit, img_url))
        def shuffle(self):
            for i in range(len(self.cards)-1, 0, -1):
                rand_num = random.randint(0, i)
                self.cards[i], self.cards[rand_num] = self.cards[rand_num], self.cards[i]
        class Card:
            def __init__(self, value, suit, img):
                self.value = value
                self.suit = suit
                self.img = img                
dealer = Dealer()
deck = dealer.Deck()
deck.shuffle()

推荐阅读