So this code runs correctly...
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()
But if I add while True:
to the play_game(self)
function like this...
def play_game(self):
while True:
self.add_card()
print(self.player.cards)
It says it can not pop()
from an empty list. So I assume the function within the while loop is not able to access the variable self.player.cards
, within the same instance as the correctly stated code does. Am I right about that?
Basically I just want to understand why this doesn't work, and what is going on...?
I do apologize if my wording is not accurate, I am new to Python...
Thanks!
question from:
https://stackoverflow.com/questions/65894775/function-in-a-function-in-a-while-loop-can-not-update-an-outside-class-variable 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…