Search code examples
pythonclassoopmethodsuser-input

Why is my instance variable coming up as undefined when I ask for user input in my init method


When I ask the user for input into my class the variable comes up as undefined. When i run it in my __init__ method

import random
import math
players=[]
player_names=[]
cards=[2,3,4,5,6,7,8,9,'kings','queens','aces']
class  Player:
    def __init__(self,name,money,cardl,bust,bet=None):
        
        self.name=name
        self.name=input('enter in your name')
        while cls.name  in player_names:
                print('username taken')
                cls.name=input('Enter in name')
        self.money=money
        money=0
        self.bet=bet
        bet=float(input("What is your bet"))
        self.busted=busted
        self.cardl=[]
        self.cardl.append(random.sample(cards,1))
        self.cardl.append(random.sample(cards,1))
        self.busted=False
player=Player(name,money,cardl,bust,bet)
players.append(player)
print('Welcome',player.name)
 
class dealer(Player):
        pass

I expected for the user to be allowed to start inputting values into the variables but I got

player=Player(name,money,cardl,bust,bet)
NameError: name 'name' is not defined

So I decided to run the __init__ method by:

__init__()

NameError: name '__init__' is not defined


Solution

  • Your variables do not yet exist when you call the class constructor, so the object cannot be created. You could initialize them empty, but then they should be initialized correctly right away. The check for the player name can be implemented this way:

    import gc
    
    player_name_list = []
    
    # get all the current player names
    for obj in gc.get_objects():
        if isinstance(obj, Player):
            player_name_list.append(obj.name)
    
    name=input('enter in your name')
    while name in player_name_list:
        print('username taken')
        name=input('Enter in name')