简体   繁体   中英

NameError: name 'Class' is not defined (Python)

So I'm trying to make Save and Load files for a text based game... Saving works, and overwrites the save if you save again. But loading brings up the NameError.

def save():
    my_file = open("save.txt", "w")
    my_file.write(Class + "\n")
    my_file.write(level + "\n") 
    my_file.write(str(hp) + "\n")
    my_file.write(str(atk) + "\n")
    my_file.write(str(Def) + "\n")
    my_file.write(str(spd)+ "\n")
    my_file.write(str(ene)+ "\n")
    my_file.write(str(race1)+ "\n")
    my_file.close()

def load():
    infile = open("save.txt")

    lines = infile.readlines()

    line_number = 0

    while line_number < len(lines):

        Class = lines[line_number]
        level = lines[line_number + 1]
        hp = lines[line_number + 2]
        atk = lines[line_number + 3]
        Def = lines[line_number + 4]
        spd = lines[line_number + 5]
        ene = lines[line_number + 6]
        race1 = lines[line_number + 7]

        line_number += 8
        print(Class, level, hp, atk, Def, spd, ene, race1)


    infile.close()
    identify()

Above is the save and load definitions..

Here is the Class input definition:

def class_level():
        global Class
        global level
        Class = input("Please input your class: ")
        print()
        level = input("Please input your level: ")
        print()
        race()    

And here is the indentify definition:

def identify():
    global hp
    global atk
    global Def
    global spd
    global ene
    if re.match(r"warrior", Class, re.I):  <---- This is the line the error is on, Class not defined
    print()

Can someone tell me what I've done wrong? It will load the file and display it.. but then say that Class is not defined in the def identify. Thanks.

In python the way global works is that it does not only define a variable as a global variable. It adds the variable to the local namespace from the global namespace if present. If it is not present, it creates a global instance and adds that to the local namepsace. You might have Class as a variable in global namespace, but inside your identify function local namespace, Class is not present. You will need to add Class to the local namespace of identify . You do that by adding the line global Class . Now the local namespace has a reference to the the variable Class

def identify():
    global hp
    global atk
    global Def
    global spd
    global ene
    # You need to mention global Class as well
    global Class
    if re.match(r"warrior", Class, re.I): 
    print()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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