while循环中函数中的函数是否不能更新外部类变量



因此此代码可以正确运行。。。

class Deck:
def __init__(self):
self.cards = []
for i in range(6):
self.cards.append(i)
class Player:
def __init__(self):
self.cards = []

class Game:
def __init__(self):
self.player = Player()
self.deck = Deck()

def play_game(self):
self.add_card()
print(self.player.cards)

def add_card(self):
self.player.cards.append(self.deck.cards.pop())       

game = Game()
game.play_game() 

但是如果我像这样把while True:加到play_game(self)函数中。。。

def play_game(self):
while True: 
self.add_card()
print(self.player.cards)

它说它不能从空列表中pop()。因此,我假设while循环中的函数无法访问变量self.player.cards,与正确声明的代码处于同一实例中。我说得对吗?

基本上,我只想了解为什么这不起作用,以及发生了什么。。。?

如果我的措辞不准确,我深表歉意,我是Python的新手。。。

谢谢!

在我看来,你已经从牌组中抽出了所有6张牌,并且它的cards列表已经清空

最新更新