0

我有以下代码:

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

它没有做我想要的 - 我希望对jobin的更改other_function反映在全局变量USERS中,以便函数save将正确的数据输出到文件(文件中的第 2 行将是“Nothing”而不是“Mow”)。我试过声明global USERSother_function但没有奏效。任何帮助表示赞赏。

4

2 回答 2

2

您必须意识到,除了它的值之外,jobinother_function与 equals 无关。所以无论你做什么,它都不会改变。它与 . 无关。因此,将您的代码更改为:USERSUSERS[0].job[0]USERSglobal

def main():
    global USERS

    jobs = ["Mow", "Rake", "Mulch"]
    USERS = [User("Fred", jobs), User("Mark", jobs), User("Greg", jobs)]
    USERS[0].jobs[0] = other_function(USERS[0].jobs[0])

    save(USERS)

def other_function(job):
    job = 'Nothing' #do something on the value
    return job
于 2013-07-11T17:19:07.013 回答
0

我不相信你USERS in other_function在将它传递给你的save()函数之前实际上是在修改它。

于 2013-07-11T17:22:03.587 回答