在我的学校项目中,我必须创建全局“客户列表”功能,所以我不必每次在其他功能中需要此文件时打开我的文件。这里说没有定义client_list:
global client_list
def clients():
client_list = []
with open("svi.txt","r") as f:
every_part = ["username","password","name","lastname","role"]
for r in f.readlines():
dicct = {}
bla = r.strip().split("|")
count = 0
for i in bla:
dicct[every_part[count]] = i
count += 1
client_list.append(dicct)
def log(file_path,user,password,delimiter):
for r in client_list:
n = r.strip().split(delimiter)
username = n[0]
passwordd = n[1]
role = n[4]
while username == user and passwordd == password:
if role == "buyer":
return buyer_menu2()
elif role == "manager":
return menager_menu2()
elif role == "seller":
return seller_menu2()
return False
def login():
x = False
while x == False:
user = input("Username: ")
password = input("Password: ")
x = log("svi.txt",user,password,"|")
if x == False:
print()
print("Wrong username or password, please try again. ")
print()
print()
login()
答案 0 :(得分:0)
如上所述here,Python中的global
关键字用于在本地上下文中突变或定义全局变量 。您不需要它在已经全局范围内声明全局变量,因此在您编写global client_list
的位置时,您可以通过编写类似client_list = []
需要global
关键字在您打算修改全局client_list
变量的任何函数中。因此,例如,如果您打算将clients()
函数附加到(或以其他方式改变)全局client_list
,则它应包含global client_list
声明。
def clients():
global client_list
with open("svi.txt","r") as f:
<the rest of your function>
答案 1 :(得分:0)
如果通过&#34;全局函数&#34;,您实际上是指&#34;全局变量&#34;,以下内容应该有所帮助:
client_list = []
def clients():
global client_list
client_list = []
with open("svi.txt","r") as f:
every_part = ["username","password","name","lastname","role"]
for r in f.readlines():
dicct = {}
bla = r.strip().split("|")
count = 0
for i in bla:
dicct[every_part[count]] = i
count += 1
client_list.append(dicct)
def log(file_path,user,password,delimiter):
# No need to declare client_list as global for reading it
for r in client_list:
n = r.strip().split(delimiter)
username = n[0]
passwordd = n[1]
role = n[4]
while username == user and passwordd == password:
if role == "buyer":
return buyer_menu2()
elif role == "manager":
return menager_menu2()
elif role == "seller":
return seller_menu2()
return False
def login():
x = False
while x == False:
user = input("Username: ")
password = input("Password: ")
x = log("svi.txt",user,password,"|")
if x == False:
print()
print("Wrong username or password, please try again. ")
print()
print()
login()
所以不要将client_list声明为文件顶部的全局,而是要在那些要更改其内容的函数中声明。
根据评论进行修改:
当然,您必须在程序中至少调用一次clients
才能最初填写您的client_list。这不是我的代码,因为我只是拿走了你的代码,并假设你已经在其他地方做过了。