[英]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.
但是加载会带来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: 这是indentify定义:
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.
它将加载文件并显示它。.但是然后说def标识中未定义Class。 Thanks.
谢谢。
In python the way global works is that it does not only define a variable as a global variable. 在python中,全局工作方式不仅是将变量定义为全局变量。 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. 您可能在全局名称空间中将
Class
作为变量,但是在您的identify
函数本地名称空间中, Class
不存在。 You will need to add Class
to the local namespace of identify
. 您将需要添加
Class
到的本地命名空间identify
。 You do that by adding the line global Class
. 您可以通过添加行
global Class
。 Now the local namespace has a reference to the the variable Class
现在,本地名称空间具有对变量
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.