class - 嵌套 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 方法时,卡片在调试器中显示没有?
解决方案
怎么了:
'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()
推荐阅读
- javascript - 无法理解为什么在客户端控制台上找不到我的 js 文件
- javascript - Vuetify 自动完成 - 设置初始搜索值?
- python - Python:从 csv 中提取数据作为变量并插入基本文件(NAPALM 配置)
- node.js - Node.js 文档中嵌套对象的 MongoDB 自动增量
- javascript - 如何使用 npm 包
- url-rewriting - URL 从尾随字符串重写为 GET 变量
- java - JSON 解析错误:无法反序列化 ArrayList 的实例
- java - 如何使用 gdx-gamesvcs 将游戏数据保存到云端?
- amazon-web-services - 如何在两个不同的 AWS 区域对同一用户进行身份验证?
- c++ - 以指定字符结束输入流,例如“|”?