开发者

How do I make a variable made out of a string global in python?

I'm trying to make a blackjack game. I've made functions for drawing 开发者_高级运维cards and checking if sum in one's hand exceeds 21 but only for 3 players. That was easy I had 3 lists.

But I want to do it for N number of players so I want to keep my functions and make another one that switches between players and their hands.

def create_hands():
global total_players
for x in range(1, total_players+1):
    vars()["hand_%d" % x] = []
    print hand_1

I want to create as many hands as in hand_1, hand_2, etc... for as many N players (total_players)

Because of the code above i get an global name 'hand_1' is not defined error

So it all comes down to:

  1. How do I make "hand_%d" % x global ?

  2. Is there a better way to do it ?


Yes, there is a better way. Simply create a list of lists. Playing with vars should be ommited, if possible. It's really hard to read and debug and you will regret that attitude lately. When you create a list like players -> hand -> cards, or even a dict of players like players['player1'][3] for player's one third card, you will be much more happy with that.


The problem you are running into is that vars() is an alias for locals(), which has the following comment in the official documentation:

Note: The contents of this dictionary should not be modified; 
changes may not affect the values of local and free variables 
used by the interpreter.

In other words, adding keys to vars() does NOT necessarily update the local var iables table (which is why you're getting the global name hand_1 is not defined error - vars()[ "hand_1" ] doesn't make hand_1 into a local variable).

As Gandi mentioned, there are far easier ways to do what you are trying to do - use a list of lists or something similar. There are far more conventional ways to solve this problem than creating arbitrarily-named local variables.


Yes, it is possible to do that. Replace

vars()["hand_%d" % x] = []

with

globals()["hand_%d" % x] = []

Be warned however that this solution is kinda hackish and can easily lead to problems (difficulty in maintenance, losing track of the spontaneously created variables, etc.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜