2
votes

I was trying to do some code when I spotted this error. I first define the player class with a name a param1 and param2. When I run the game function and i try to create an instance of the player class inside, I get the UnboundLocalError error. Here is my code:

class player(object):

    def __init__ (self, name, param1 = None, param2 = None):

        self.param1 = param1
        self.param2 = param2
        self.name = name

def game(n = int(raw_input('How many players? '))):

    playerList = [] 

    for x in range(n):
        playerList.append(player(raw_input('Player %i: ' %(x+1))))

    for player in playerList:
        player.param1 = int(raw_input('%s, how many do you predict? ' %(player.name.upper())))

So basically, my problem is that python doesn't let me create an instance of a class inside a function. I have searched a lot, but I have not found what I was searching for. Thanks in advance!

1
Default variables are calculated during parsing, so it's not a good idea to add raw_input inside function arguments, as it is going to be called even if you don't run this function ever. - Ashwini Chaudhary

1 Answers

6
votes

You use the variable name player in for player in playerList, but your class is also named player. Since you assign a value to that name (in the for loop), Python treats it as a local variable, so you can't access the global class of that name.

The best solution is to change your class name to Player with a capital P. The convention in Python is for classes to start with an uppercase letter.

(The reason the error occurs on the earlier line is that Python decides which variables are local when parsing the function. Since you used player as the target of the for loop, it is marked as local, but at the time you first access it, when trying to access the class, no value is assigned to that local variable.)