我已经稍微简化了代码,因为它是大型烧瓶项目的一部分。但问题仍然存在:
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(("的输出相等。但是输出为none,当您想要使用"deck.shuffle(("时,您正试图获得none的长度。
如何修复:
只需调用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()