简体   繁体   English

为什么我会收到一个全局名称错误

[英]why am i getting a global name error

I am currently encountering the following error: 我目前遇到以下错误:

NameError: global name 'player1_unam' is not defined

If somebody could please look through the following code and give me a soultion to the problem it would be greatly appreciated. 如果有人可以浏览以下代码,并给我一个解决问题的灵感,将不胜感激。

I alpologise in advance because I know it is very messy and inefficient code but i am only a beginner in python. 我事先致敬,因为我知道这是非常混乱且效率低下的代码,但我只是python的初学者。

import os 
import random
from random import randint
game_won = False
p1_playing = True
p2_playing = True
class start_game(object):
    def __init__(self):
        suspect = ["Miss Scarlet","Colonel Mustard","Mrs. White","Reverend Green","Mrs. Peacock","Professor Plum"] 
        weapon = ["Candlestick","Dagger","Lead Pipe","Revolver","Rope","Spanner"]
        room = ["Kitchen","Ballroom","Conservatory","Billiard Room","Library","Study","Hall","Lounge","Dining Room","Cellar"]
        rndsuspect = random.randrange(0, 5 ,1)
        rndweapon = random.randrange(0,5,1)
        rndroom = random.randrange(0,9,1)
        answers = []
        answers.append(suspect[rndsuspect])
        answers.append(weapon[rndweapon])
        answers.append(room [rndroom])      
        print answers[0]
        print answers[1]
        print answers[2]

class game_type:
    def __init__(self):
        select_game = raw_input("Do you want to start the game? ")
        lstchar = ["Miss Scarlet","Colonel Mustard","Mrs. White","Reverend Green","Mrs. Peacock","Professor Plum"]
        if select_game.lower() == "yes":
            player1_unam = raw_input("What is Player 1's Name? ").lower().title()
            player1_cindex = int(input('Choose A Character: Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6] '))
            player1_char = lstchar[player1_cindex - 1]
            print ("%s has chosen to play as %s") %(player1_unam,player1_char)
            player2_unam = raw_input("What is Player 2's Name? ").lower().title()
            if player2_unam == player1_unam:
                while player2_unam == self.player1_unam:
                    player2_unam = player2_unam = raw_input("You can't use the same Name as Player 1, please choose again: ")
            player2_cindex = input('Choose A Character: Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6] ')
            player2_char = lstchar[player2_cindex - 1]
            if player2_cindex == player1_cindex:
                while player2_cindex == player1_cindex:
                    print "Choose A Character Other Than: %s" %  lstchar[player1_cindex - 1]
                    player2_cindex = int(input('Choose A Character: Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6] '))
                    player2_char = lstchar[player2_cindex - 1]
                    print ("%s has chosen to play as %s") %(player2_unam,player2_char)

class dice_roll(game_type):
    def __init__(self, game_type):
        final_suggestion = False
        suggested_suspect = ["Miss Scarlet","Colonel Mustard","Mrs. White","Reverend Green","Mrs. Peacock","Professor Plum"] 
        suggested_weapon = ["Candlestick","Dagger","Lead Pipe","Revolver","Rope","Spanner"]
        rolled_room = ["Kitchen","Ballroom","Conservatory","Billiard Room","Library","Study","Hall","Lounge","Dining Room","Cellar", "Corridor"]
        current_player = [player1_unam,player2_unam]
        chosen_room = []
        player1_room = []
        player2_room = []
        suggestion = []
        correct_elements = []
        introom = random.randrange(0,10,1)
        super(dice_roll,self). __init__(self)
        current_turn = 0
        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":
                dice = random.randrange(1,6,1)
                pass
                print "You have rolled a %d" % dice
                if dice == 1:
                    print "%s is now in the Corridor" % current_player[current_turn]
                    if current_turn == 0:
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = rolled_room[introom]
                elif dice == 2:
                    introom = random.randrange(0,10,1)
                    print "You are now in the %s"  % rolled_room[introom]                   
                    if current_turn == 0:
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = rolled_room[introom]                  
                elif dice == 3:
                    print "%s is now in the Corridor" % current_player[current_turn]
                    if current_turn == 0:
                        player1_room = rolled_room[10]
                    else:
                        player2_room = rolled_room[10]
                elif dice == 4:
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d] "  % (rolled_room[introom], introom + 1)
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d]" % (rolled_room[introom], introom + 1)
                    if current_turn == 0:
                        introom = int(input("Which Room Do You Choose? "))
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = int(input("Which Room Do You Choose? "))
                        player2_room = rolled_room[introom]
                elif dice == 5:
                    print "%s is now in the Corridor" % current_player[current_turn]
                    if current_turn == 0:
                        player1_room = rolled_room[10]
                    else:
                        player2_room = rolled_room[10]
                elif dice == 6:
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d] "  % (rolled_room[introom], introom + 1)
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d]" % (rolled_room[introom], introom + 1)
                    introom = random.randrange(0,10,1)
                    print "You can move to the %s [%d]" % (rolled_room[introom], introom + 1)
                    if current_turn == 0:
                        player1_room = int(input("Which Room Do You Choose? "))
                        player1_room = rolled_room[introom]
                    else:
                        player2_room = int(input("Which Room Do You Choose? "))
                        player2_room = rolled_room[introom]                   
                if player1_room == "Cellar" or player2_room == "Cellar":
                        if raw_input("Do you want to make a final suggestion? ").lower == "yes":
                            final_suggestion = True
                elif player1_room != "Corridor" and player1_room != "Cellar" or player2_room != "Corridor" and player2_room != "Cellar":
                    suggestion_index = int(input("Who do you think committed the crime? Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6]"))
                    suggestion.append(suggested_suspect[suggestion_index - 1])
                    suggestion_index = int(input("What do you think was used to commit the crime? Candlestick [1], Dagger [2], Lead Pipe[3], Revolver[4], Rope[5], Spanner[6] "))
                    suggestion.append(suggested_weapon[suggestion_index - 1])
                    if current_turn == 0:
                        suggestion.append(player1_room)
                    else:
                        suggestion.append(player2_room)
                        if suggestion [0] == start_game.answers [0]:
                            correct_elements.append(suggestion[0])
                        elif suggestion [1] == start_game.answers [1]:
                            correct_elements.append(suggestion[1])
                        elif suggestion [2] == start_game.answers [2]:
                            correct_elements.append(suggestion[2])
                        intcorrect = len(correct_elements)            
                    if final_suggestion == True:
                            suggestion_index = int(input("Who do you think committed the crime? Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6]"))
                            suggestion.append(suggested_suspect[suggestion_index - 1])
                            suggestion_index = int(input("What do you think was used to commit the crime? Candlestick [1], Dagger [2], Lead Pipe[3], Revolver[4], Rope[5], Spanner[6] "))
                            suggestion.append(suggested_weapon[suggestion_index - 1])
                            suggestion_index = int(input("Where do you think the crime was committed? Kitchen [1],Ballroom [2],Conservatory [3], Billiard Room [4], Library [5], Study [6], Hall [7], Lounge [8], Dining Room [9], Cellar [10]"))
                            suggestion.append(rolled_room[suggestion_index - 1])
                            if suggestion[0] == start_game.answers[0] and suggestion [1] == start_game.answers [1] and suggestion [2] == start_game.answers [2]:
                                game_won = True
                                print "%s Has won the game :D" %current_player[current_turn]
                                print "%s committed the murder with the %s in the %s" %(start_game.answers[0],start_game.answers[1],start_game.answers[2])
                                print "Thankyou for playing CLUEDO"
                                if raw_input("Would you like to play again? ").lower == "yes":
                                    run_game = game_type(__init__)          
                elif player1_room != "Corridor" and player1_room != "Cellar" or player2_room != "Corridor" and player2_room != "Cellar":
                        suggestion_index = int(input("Who do you think committed the crime? Miss Scarlet[1], Colonel Mustard [2], Mrs. White [3], Reverand Green [4], Mrs. Peacock [5], Professor Plum [6]"))
                        suggestion.append(suggested_suspect[suggestion_index - 1])
                        suggestion_index = int(input("What do you think was used to commit the crime? Candlestick [1], Dagger [2], Lead Pipe[3], Revolver[4], Rope[5], Spanner[6] "))
                        suggestion.append(suggested_weapon[suggestion_index - 1])
                        if current_turn == 0:
                            suggestion.append(player1_room)
                        else:
                            suggestion.append(player2_room)
                        if suggestion [0] == start_game.answers [0]:
                           correct_elements.append(suggestion[0])
                        elif suggestion [1] == start_game.answers [1]:
                            correct_elements.append(suggestion[1])
                        elif suggestion [2] == start_game.answers [2]:
                            correct_elements.append(suggestion[2])
                        intcorrect = len(correct_elements)
                if intcorrect == 0:
                    print "None of those facts are correct"
                    del correct_elements[0:len(correct_elements)]
                    del suggestion[0:len(suggestion)]
                    else:
                        shown_card = random.choice(correct_elements)
                        print "You got %s correct" %shown_card
                        del correct_elements[0:len(correct_elements)]
                        del suggestion[0:len(suggestion)]
            current_turn += 1                
            if current_turn == 2:
                current_turn = 0

run_game = game_type()
suspectinfo = start_game()           
roll = dice_roll(game_type)

run_game()#.__init__()
suspectinfo()#.__init__()
roll()

Thankyou for your help 谢谢您的帮助

You need to use 您需要使用

self.player1_unam

instead of 代替

player1_unam

Otherwise, when you make the initial assignment, a local variable is created, and when you are trying to dereference (access) it, Python first look for a local variable and then a global one, and failing both times it gave you that error. 否则,当您进行初始分配时,将创建一个局部变量,并在尝试取消引用(访问)时,Python首先寻找一个局部变量,然后寻找一个全局变量,并且两次失败均导致该错误。

You need to use self.player1_unam because python is looking in the global namespace instead of the local one (inside of the class where it is defined). 您需要使用self.player1_unam因为python在global名称空间而不是本地名称空间中(在定义该名称的类内部)进行查找。

for example, the following could be a value in the global namespace, while self.player1_unam is defined in the class: 例如,以下可以是在全局命名空间的值,而self.player1_unam在类定义:

def player1_unam():
    print "I am in the global namespace!"

or the variable: 或变量:

player1_unam="I am in the global namespace!"

or the class: 或班级:

class player1_unam(object):
    pass

It is notable that you will have to change EVERY use of the player1_unam to self.player1_unam in order to fix this. 值得注意的是,你将不得不改变每次使用的player1_unamself.player1_unam为了解决这个问题。

Why not just make player one name a variable from the start? 为什么不从一开始就让玩家一个名字成为变量? I feel that would be better. 我觉得那会更好。

 class game_type:
    def __init__(self):
        global  player1_unam
        ...
        player1_unam = raw_input("What is Player 1's Name? ").lower().title()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM