如何将变量传递给不同的函数并修改该变量?

时间:2018-04-04 21:10:42

标签: python-3.x function asynchronous

例如,假设我在这里有“伪”代码:

def on_start():
    members = {'guy1':'1234','guy2':'5678'}

def function1():
    # we do something with the dict, let's say, print each member
    print(members.keys())

# ex: new_member = {'guy3':'9012'}
def function2(new_member):
    # something happened so the dict now has a new member
    members.update(new_member)

on_start()
while True:
    function1() # run on a separate thread
    # the condition would be "if I triggered the "add_member" event, do function2
    if condition:
        function2(input())

我基本上有一个在脚本启动时调用的函数,它初始化字典,然后有function1()循环并使用该字典,如果从用户输入添加了新成员,那么{{调用1}}应该将成员添加到dict中,因此下次调用function2()时,它会找到新添加的成员。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

问题是你的'dict'变量不能在你的on_start()函数范围之外访问。我能够通过对您的代码进行一些小调整来获得您想要的结果:

def on_start():
    return {'guy1':'1234','guy2':'5678'}

def function1(dict):
    # we do something with the dict, let's say, print each member
    for key, value in dict.items():
        print (key, value)

# ex: new_member = {'guy3':'9012'}
def function2(new_member):
    # something happened so the dict now has a new member
    dict.update(new_member)

dict = on_start()
while True:
    function1(dict) # run on a separate thread
    name = raw_input("What is your name? ")
    id = raw_input("What is your id? ")

    if name and id:
        function2({name: id})

总结一下,我打电话给on_start初始化并返回你的字典。

然后代码进入你的while循环,其中调用了function1。如果用户输入是成功的(我没有做任何输入验证,生病让你这样做)调用函数2来更新字典。然后这个过程重复

还建议您将'dict'的名称更改为@zwer建议的非内置名称。

我不认为这里需要产生另一个线程,这可能会有问题,因为你会同时读/写相同的变量。