minimatt
minimatt

Reputation: 59

I keep getting a naming error when i try to run this piece of code (Python)

class game_type(object):
    def __init__(self):
        select_game = raw_input("Do you want to start the game? ")
        if select_game.lower() == "yes":
            player1_title = raw_input("What is Player 1's title? ").lower().title()


class dice_roll(object,game_type):
    current_turn = 1
    current_player = [player1_title,player2_title]
    def __init__(self):
        while game_won == False and p1_playing == True and p2_playing == True: 
            if raw_input("Type 'Roll' to start your turn  %s" %current_player[current_turn]).lower() == "roll":

I keep getting an error which reads: NameError: name 'player1_title' is not defined

I understand that title is a function so i did try using player1_name and player1_unam but these also returned the same error :(

can somebody please help

All answers are greatly appreciated

Upvotes: 1

Views: 110

Answers (1)

Schlueter
Schlueter

Reputation: 4029

There are a number of things leading to the NameError.

For one, the __init__ method of game_type does not save any data. To assign instance variables you have to specify the class instance with self.. If you don't, you're just assigning local variables.

Secondly, you must explicitly call a parent class's __init__ function with super() if you are creating a new one in a child class and still want the effects of the parent's.

So basically, your code should be

# Class names should be CapCamelCase
class Game(object):                                                                
    def __init__(self):                                                    
        select_game = raw_input("Do you want to start the game? ")         
        if select_game.lower() == "yes":                               
            self.player1_title = raw_input("What is Player 1's title? ").lower().title()
            # Maybe you wanted this in DiceRoll?
            self.player2_title = raw_input("What is Player 1's title? ").lower().title()

# If Game were a subclass of something, there would be no need to 
# Declare DiceRoll a subclass of it as well
class DiceRoll(Game):                                                      
    def __init__(self):                                                   
        super(DiceRoll, self).__init__(self)                               
        game_won = False                                                   
        p1_playing = p2_playing = True                                     
        current_turn = 1                                                   
        current_players = [self.player1_title, self.player2_title]    
        while game_won == False and p1_playing == True and p2_playing == True:
            if raw_input("Type 'Roll' to start your turn %s" % current_players[current_turn]).lower() == "roll":
                pass

Upvotes: 5

Related Questions