我有以下代码:
USERS = None
class User(object):
name = ""
jobs = []
def __init__(self, name, jobs):
self.name = name
self.jobs = jobs
def main():
global USERS
jobs = ["Mow", "Rake", "Mulch"]
USERS = [User("Fred", jobs), User("Mark", jobs), User("Greg", jobs)]
other_function(USERS[0].jobs[0])
return
def other_function(job):
job = "Nothing"
save(USERS)
return
def save(users):
f = open("save_file", "w")
for user in users:
f.write(user.name+"\n")
for job in user.jobs:
f.write(job+"\n")
return
if __name__=='__main__':
main()
raw_input()
输出文件“save_file”如下所示:
Fred
Mow
Rake
Mulch
Mark
Mow
Rake
Mulch
Greg
Mow
Rake
Mulch
它没有做我想要的 - 我希望对job
in的更改other_function
反映在全局变量USERS
中,以便函数save
将正确的数据输出到文件(文件中的第 2 行将是“Nothing”而不是“Mow”)。我试过声明global USERS
,other_function
但没有奏效。任何帮助表示赞赏。