Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

python - Function in a function in a while loop can not update an outside class variable?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

seems to me that you have drawn all 6 cards from the deck and its cards list has gone empty


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...